使用 pyparsing 解析简单语法时出错

Error in parsing a simple grammar with pyparsing

我正在尝试使用串联、析取和 kleene star 来解析一个简单的正则表达式语法。我的语法和测试是这样的:

from pyparsing import Word, nums, Forward, Suppress, OneOrMore

#A grammar for a simple class of regular expressions
number = Word(nums)('number')
lparen = Suppress('(')
rparen = Suppress(')')

expression = Forward()('expression')

concatenation = expression + expression
concatenation.setResultsName('concatenation')

disjunction = lparen + OneOrMore(expression + Suppress('|')) + expression + rparen
disjunction.setResultsName('disjunction')

kleene = lparen + expression + rparen + Suppress('*')
kleene.setResultsName('kleene')

expression << number | concatenation | disjunction | kleene

#Test a simple input
tests = """
7
23
(7)*
(45)*
(1|2|3)
((2)*|3)
((0|1))*
""".splitlines()

for t in tests:
    print t
    print expression.parseString(t)
    print

但是,程序在第一次测试时就失败了:

Traceback (most recent call last):
  File "main.py", line 34, in <module>
    print expression.parseString(t)
  File "/home/elliot/miniconda2/lib/python2.7/site-packages/pyparsing.py", line 1216, in parseString
    raise exc
pyparsing.ParseException: Expected W:(0123...) (at char 0), (line:1, col:1)

这里有什么问题?此外,对于我的语法的任何其他反馈(即我如何做事 better/simpler)也将不胜感激。

初试不"7"。第一个测试是 "",因为您的 tests 字符串以空行开头。 "" 与您的语法中的有效表达式不匹配。