Pyparsing 有一些用于匹配嵌套括号文本的内置函数 - 在您的情况下,您并不是真正尝试提取括号的内容,您只是想要最外面的“(”和“)”之间的文本。
from pyparsing import White, Keyword, nestedExpr, lineEnd, Suppress
insource = """
annotation (
foo1(k=3),
bar(
x=0.29,
y=0,
bar1(
x=3, y=4),
width=0.71,
height=0.85),
foo2(System(...))
"""
barRef = White(' \t') + Keyword('bar') + nestedExpr() + ',' + lineEnd
out = Suppress(barRef).transformString(insource)
print out
Prints
annotation (
foo1(k=3),
foo2(System(...))
编辑:解析操作以不删除以“85”结尾的 bar() 调用:
barRef = White(' \t') + Keyword('bar') + nestedExpr()('barargs') + ','
def skipEndingIn85(tokens):
if tokens.barargs[0][-1].endswith('85'):
raise ParseException('ends with 85, skipping...')
barRef.setParseAction(skipEndingIn85)