简体   繁体   English

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

[英]Error in parsing a simple grammar with pyparsing

I'm trying to parse a simple regex grammar with concatenation, disjunction, and kleene star. 我正在尝试使用级联,分离和克利恩星解析一个简单的正则表达式语法。 My grammar and tests look like this: 我的语法和测试如下所示:

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

However, the program fails on the very first test: 但是,该程序在第一次测试时失败:

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)

What's the problem here? 这是什么问题 Also, any other feedback on my grammar (ie how I could have done things better/simpler) would be appreciated as well. 同样,对我的语法的任何其他反馈(即,我如何能做得更好/更简单)也将不胜感激。

The first test is not "7" . 第一个测试不是"7" The first test is "" , because your tests string starts with an empty line. 第一个测试是"" ,因为您的tests字符串以空行开头。 "" does not match a valid expression in your grammar. ""与您语法中的有效表达式不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM