当超过两个匹配时,Pyparsing OR 操作使用最短的字符串

Pyparsing OR operation use shortest string when more than two match

我需要解析一些语句,但希望灵活地使用多个词来表示语句的含义。

例如

string = """
start some statement end
other stuff in between
start some other statement.
other stuff in between
start another statement
"""

在这种情况下,end. 和行尾是表示结束的标记 我正在寻找的声明。

我尝试了以下方法:

from pyparsing import restOfLine, SkipTo

skip_to_end_of_line = restOfLine
skip_to_dot = SkipTo('.', include=False)
skip_to_end = SkipTo('end', include=False)

statement = 'start' + skip_to_end_of_line^skip_to_dot^skip_to_end

statement.searchString(string)

([(['start some statement end\nother stuff in between\nstart some other statement'], {}), (['start', ' another statement'], {})], {})

通过使用 OR 函数,它 return 是最大的字符串,如果有两个以上的匹配项,我想 OR 到 return 最短的字符串 结果

([(['start', ' some statement end'], {}), (['start', ' some other statement.'], {}), (['start', ' another statement'], {})], {})

SkipTo 是 pyparsing 的不可预测特征之一,因为输入数据很容易导致比预期更多或更少的跳过。

试试这个:

term = LineEnd().suppress() | '.' | 'end'
statement = 'start' + OneOrMore(~term + Word(alphas)) + term

这个表达式不是盲目跳过,而是迭代地查找单词,并在找到您的终止条件之一时停止。

如果你想要实际的正文字符串而不是单词集合,你可以使用originalTextFor:

statement = 'start' + originalTextFor(OneOrMore(~term + Word(alphas))) + term