Python正则表达式:查找不包含子字符串的子字符串

Sol*_*ris 4 python regex

这是一个例子:

a = "one two three four five six one three four seven two"
m = re.search("one.*four", a)
Run Code Online (Sandbox Code Playgroud)

我想要的是找到从"一"到"四"的子串,其中不包含子串"两".答案应该是:m.group(0)="一三四",m.start()= 28,m.end()= 41

有没有办法用一条搜索线做到这一点?

Kob*_*obi 6

您可以使用此模式:

one(?:(?!two).)*four
Run Code Online (Sandbox Code Playgroud)

在匹配任何其他字符之前,我们检查我们没有开始匹配"两个".

工作示例:http://regex101.com/r/yY2gG8


sat*_*oru 2

您可以使用否定先行断言(?!...)

re.findall("one(?!.*two).*four", a)
Run Code Online (Sandbox Code Playgroud)