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

时间:2017-02-10 19:19:07

标签: python pyparsing

我尝试使用连接,析取和kleene星解析一个简单的正则表达式语法。我的语法和测试看起来像这样:

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)

这里的问题是什么?此外,我的语法的任何其他反馈(即我如何做得更好/更简单)也将受到赞赏。

1 个答案:

答案 0 :(得分:2)

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