正则表达式:如何查找不包含特定单词的子字符串

时间:2020-01-01 07:12:41

标签: python regex

我有这个字符串;

string = "STARTcandyFINISH  STARTsugarFINISH STARTpoisonFINISH STARTBlobpoisonFINISH STARTpoisonBlobFINISH"

我想匹配并捕获出现在STARTFINISH之间的所有子字符串,但前提是该子字符串中没有出现“ poison”一词。如何排除该单词并仅捕获所需的子字符串?

re.findall(r'START(.*?)FINISH', string)

所需的捕获组:

candy
sugar

1 个答案:

答案 0 :(得分:1)

使用回火点,我们可以尝试:

string = "STARTcandyFINISH  STARTsugarFINISH STARTpoisonFINISH STARTBlobpoisonFINISH STARTpoisonBlobFINISH"
matches = re.findall(r'START((?:(?!poison).)*?)FINISH', string)
print(matches)

此打印:

['candy', 'sugar']

有关正则表达式模式如何工作的解释,我们可以仔细看看:

(?:(?!poison).)*?

这使用了回火点技巧。只要后面是不是 poison,它将一次匹配一个字符。