我正在尝试使用pyparsing解析一种带有撇号的小语言,一切都很好,直到突然间我开始收到无法调试的神秘错误。
我将解析器缩减为导致错误的最小内容:
作为我要尝试做的事的示例,请考虑一种语言,其中包含一个,并嵌套一个列表。
例如1(11)1(1((11)1))
可以这样解析:
from pyparsing import *
sound=Regex(r"1")
beat=sound ^ nestedExpr(content=sound)
tune=OneOrMore(beat)
print(tune.parseString("1"))
print(tune.parseString("11"))
print(tune.parseString("(1)"))
print(tune.parseString("(1(1))"))
但是如果我尝试添加撇号,则基本单位改为'1
:
例如'1('1'1)'1('1(('1'1)'1))
sound=Regex(r"'1")
beat=sound ^ nestedExpr(content=sound)
tune=OneOrMore(beat)
#These all work as expected
print(tune.parseString("'1"))
print(tune.parseString("'1'1"))
print(tune.parseString("('1)"))
#but
print(tune.parseString("('1('1))"))
引起异常
pyparsing.ParseException: Expected {Re:("'1") ^ nested () expression}, found '1' (at char 5), (line:1, col:6)
[谁能告诉我如何使第二个示例像第一个示例那样工作,以便在用1
替换每个'1
之后,第一个示例接受的任何字符串都将被第一个示例接受吗?
nestedExpr
的默认值为ignoreExpr=quotedString
。这将尝试匹配前导'
作为引号。通过设置ignoreExpr=None
将其禁用:
>>> sound=Regex(r"'1")
>>> beat=sound ^ nestedExpr(content=sound, ignoreExpr=None)
>>> tune=OneOrMore(beat)
>>> print(tune.parseString("('1('1))"))
[["'1", ["'1"]]]