我想编写一个匹配字符串的表达式语法,如下所示:
words at the start ONE|ANOTHER wordAtTheEnd
---------^-------- ----^----- --^--
A: alphas B: choice C: alphas
然而,问题是部分A可以包含来自部分B的关键字“ONE”或“ANOTHER” ,因此只有最后一次出现的选择关键字应该与部分B匹配。这里有一个例子:字符串
ZERO ONE or TWO are numbers ANOTHER letsendhere
应该被解析成字段
A: "ZERO ONE or TWO are numbers"
B: "ANOTHER"
C: "letsendhere"
pyparsing
我尝试了表达式的“ ” -stopOn
关键字:OneorMore
choice = pp.Or([pp.Keyword("ONE"), pp.Keyword("OTHER")])('B')
start = pp.OneOrMore(pp.Word(pp.alphas), stopOn=choice)('A')
end = pp.Word(pp.alphas)('C')
expr = (start + choice) + end
但这不起作用。对于示例字符串,我得到ParseException
:
Expected end of text (at char 12), (line:1, col:13)
"ZERO ONE or >!<TWO are numbers ANOTHER text"
这是有道理的,因为在第一次出现而不是最后一次stopOn
出现时停止。如何编写一个在最后一次出现时停止的语法?也许我需要求助于上下文相关的语法?choice