pyparsing错误

les*_*_56 4 python parsing pyparsing

在pyparsing中我遇到了这个错误

from pyparsing import Word,alphas,nums,Or,Regex,StringEnd
ws = Regex('\s*')
dot = "."
w = Word(alphas) + (ws | dot) + StringEnd()
w.leaveWhitespace()
w.parseString('AMIT.')
Run Code Online (Sandbox Code Playgroud)

返回以下错误:

ParseException: Expected end of text (at char 4), (line:1, col:5)
Run Code Online (Sandbox Code Playgroud)

Pau*_*McG 6

| 创建"匹配第一"表达式,而不是"匹配最长".

第一种选择是正则表达式,它将匹配0个或更多的空格字符.事实上,这确实匹配,因此不解析点.

然后解析的下一个元素是StringEnd,但是解析位置仍然位于'.' - 所以,失败!

通过添加setDebug()对语法表达式的调用,可以获得更详细的输出:

>>> w = Word(alphas).setDebug() + (ws.setDebug() | dot.setDebug()) + StringEnd()
>>> w.parseString('AMIT.')
Match W:(abcd...) at loc 0(1,1)
Matched W:(abcd...) -> ['AMIT']
Match Re:('\\s*') at loc 4(1,5)
Matched Re:('\\s*') -> ['']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python26\lib\site-packages\pyparsing-1.5.6-py2.6.egg\pyparsing.py", line 1032, in parseString
    raise exc
pyparsing.ParseException: Expected end of text (at char 4), (line:1, col:5)
Run Code Online (Sandbox Code Playgroud)

为了让你的语法有效,你可以:

  • |运算符更改为^(匹配最长而不是匹配)

  • 更改正则表达式\s+而不是\s*(因此匹配需要至少一个空格)

  • 把你的第二个任期改为 Optional(dot)

一般来说,对空白的显式测试与pyparsing哲学不一致 - pyparsing与re不同.