我有这个简单的语法:
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()
内重复的内容是什么?
答案 0 :(得分:1)
这是pyparsing的每个类的错误 - 将在2.0.6中修复。