我有这个字符串;
string = "STARTcandyFINISH STARTsugarFINISH STARTpoisonFINISH STARTBlobpoisonFINISH STARTpoisonBlobFINISH"
我想匹配并捕获出现在START
和FINISH
之间的所有子字符串,但前提是该子字符串中没有出现“ poison”一词。如何排除该单词并仅捕获所需的子字符串?
re.findall(r'START(.*?)FINISH', string)
所需的捕获组:
candy
sugar
答案 0 :(得分:1)
使用回火点,我们可以尝试:
string = "STARTcandyFINISH STARTsugarFINISH STARTpoisonFINISH STARTBlobpoisonFINISH STARTpoisonBlobFINISH"
matches = re.findall(r'START((?:(?!poison).)*?)FINISH', string)
print(matches)
此打印:
['candy', 'sugar']
有关正则表达式模式如何工作的解释,我们可以仔细看看:
(?:(?!poison).)*?
这使用了回火点技巧。只要后面是不是 poison
,它将一次匹配一个字符。