如何用 PyParsing 解析这个字符串?

How to parse this string with PyParsing?

我要解析:

'APPLE BANANA FOO TEST BAR'

进入:

[['APPLE BANANA'], 'FOO', ['TEST BAR']]

这是我最近的尝试:

to_parse = 'APPLE BANANA FOO TEST BAR'
words = Word(alphas)
foo = Keyword("FOO")
parser = Group(ZeroOrMore(words + ~foo)) + foo + Group(ZeroOrMore(words))
result = parser.parseString(to_parse)

但是会return以下错误:

>       raise ParseException(instring, loc, self.errmsg, self)
E       pyparsing.ParseException: Expected "FOO" (at char 6), (line:1, col:7)

我认为问题来自 ZeroOrMore(words + ~foo)),即 "too greedy"。根据关于 SO 的几个问题,解决方案是使用 ~foo 的否定,但在这种情况下不起作用。任何帮助将不胜感激

你绝对是在正确的轨道上。您只需要在 foo 解析 words:

之前进行否定前瞻
parser = Group(ZeroOrMore(~foo + words)) + foo + Group(ZeroOrMore(words))

在最近的 pyparsing 版本中,我向 ZeroOrMoreOneOrMore 添加了一个 stopOn 参数,它做同样的事情,以减少出错的可能性:

parser = Group(ZeroOrMore(words, stopOn=foo)) + foo + Group(ZeroOrMore(words))

通过此更改,我得到:

>>> result.asList()
[['APPLE', 'BANANA'], 'FOO', ['TEST', 'BAR']]