如何用python得到最短匹配(复杂的nongreedy模式)

2024-06-16 14:59:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获得模式'''.*?''' is a [[.*?]]的最短匹配,例如

'''fermentation starter''' is a preparation to assist the beginning of the [[fermentation (biochemistry)|fermentation]]. A '''starter culture''' is a [[microbiological culture]]

它包含目标字符串

^{pr2}$

我们的想法是得到后面的字符串。为此,我使用以下python代码:

regex = re.compile("'''.*?''' is a \[\[.*?\]\]")
re.findall(regex, line)

然而,我得到的是完整的句子而不是最短的句型。请注意,我添加了“?”在限定符后使比赛以非贪婪的方式进行。我也可以用

re.findall(regex, line[30:])

为了避免第一次出现{},但我正在寻找一个更自然的解决方案。在


Tags: theto字符串reisline模式regex
2条回答

您可以使用此基于lookahead的regex:

>>> print re.findall(r"'''(?:(?!''').)*''' is a \[\[.*?\]\]", line)
["'''starter culture''' is a [[microbiological culture]]"]

(?:(?!''').)*将匹配0个或多个在下一个位置没有'''的字符,因此要确保匹配两个'''之间的最短匹配。在

RegEx Demo

如果您确定''' '''内不会有“[”,一个简单的解决方案是:

regex = re.compile("'''[^[]*?''' is a \[\[.*?\]\]")
regex.findall(line)

或者您也可以使用'执行相同的操作:

^{pr2}$

相关问题 更多 >