2016-01-20 20 views
3

我試圖讓圖案'''.*?''' is a [[.*?]]的最短匹配的句子,如如何獲得與蟒蛇最短的匹配(複雜的非貪婪模式)

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

其中包含目標字符串

'''starter culture''' is a [[microbiological culture]] 

這個想法是得到後面的字符串。爲此,我使用以下python代碼:

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

但是,我得到的是完整的句子而不是最短的模式。請注意,我添加了'?'在比賽之後以非貪婪的方式進行比賽。此外,我可以爲了逃脫的'''.*?'''第一次出現使用

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

解決這個問題,但我正在尋找一個更自然的解決方案。

回答

2

您可以使用此前瞻基於正則表達式:

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

(?:(?!''').)*將匹配0個或多個不爲下一個位置有'''從而確保兩個'''之間的匹配最短匹配任意字符。

RegEx Demo

0

如果你確信你不會有「[」內''' '''一個簡單的解決辦法是這樣的:

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

或者你也可以做同樣的事情,但與'

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