我有一个简单的语法:
word = Word(alphanums + '_')
with_stmt = Suppress('with') + OneOrMore(Group(word('key') + Suppress('=') + word('value')))('overrides')
using_stmt = Suppress('using') + Regex('id-[0-9a-f]{8}')('id')
modifiers = Optional(with_stmt('with_stmt')) & Optional(using_stmt('using_stmt'))
pattern = StringStart() + modifiers + StringEnd()似乎Optional() & Optional()错误地允许多次重复任意一个modifier,并且只标记最后一个:
>>> print dict(pattern.parseString('with foo=bar bing=baz using id-deadbeef using id-feedfeed'))
{
'with_stmt': (
[
(['foo', 'bar'], {'value': [('bar', 1)], 'key': [('foo', 0)]}),
(['bing', 'baz'], {'value': [('baz', 1)], 'key': [('bing', 0)]})
],
{'overrides':
[(([
(['foo', 'bar'], {'value': [('bar', 1)], 'key': [('foo', 0)]}),
(['bing', 'baz'], {'value': [('baz', 1)], 'key': [('bing', 0)]})
], {}), 0)]
}
),
'overrides':
(
[(['foo', 'bar'], {'value': [('bar', 1)], 'key': [('foo', 0)]}),
(['bing', 'baz'], {'value': [('baz', 1)], 'key': [('bing', 0)]})], {}
),
'id': (['id-deadbeef', 'id-feedfeed'], {}),
'using_stmt': (['id-deadbeef', 'id-feedfeed'], {'id': [('id-deadbeef', 0), ('id-feedfeed', 1)]})
}using_stmt匹配id-deadbeef和id-feedfeed,而不是向using id-feedfeed抛出错误。
奇怪的是,如果使modifiers成为非可选的,那么重定位问题就会消失,解析就会像预期的那样失败:
>>> dict(pattern.parseString('with foo=bar bing=baz using id-deadbeef using id-feedfeed'))
Traceback (most recent call last):
File "parse.py", line 10, in <module>
print dict(pattern.parseString('with foo=bar bing=baz using id-deadbeef using id-feedfeed'))
File "/path/to/lib/python2.7/site-packages/pyparsing.py", line 1139, in parseString
raise exc
pyparsing.ParseException: Expected end of text (at char 40), (line:1, col:41)切换到+而不是&也会导致它如预期的那样失败。with_stmt展示了同样的问题,并且使它成为非可选的也解决了它。
将模式标记为允许在Each()中重复的可选模式是什么?
发布于 2015-10-31 17:56:15
在每个类中,这都是一个bug --将在2.0.6中修复。
https://stackoverflow.com/questions/33448004
复制相似问题