Python 正则表达式 : find a substring that doesn't contain a substring

标签 python regex

例子如下:

a = "one two three four five six one three four seven two"
m = re.search("one.*four", a)

我想要的是找到从“一”到“四”之间不包含子串“二”的子串。 答案应该是:m.group(0) = "一三四", m.start() = 28, m.end() = 41

有没有一种方法可以用一个搜索行来做到这一点?

最佳答案

你可以使用这个模式:

one(?:(?!two).)*four

在匹配任何其他字符之前,我们会检查我们是否开始匹配“两个”。

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

关于Python 正则表达式 : find a substring that doesn't contain a substring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19750096/

相关文章:

python - 按元素添加两个元组

python - 将流量重定向到其他网络服务器

python - 使用 Python 将列中的值从 float 舍入到整数

java - 用正斜杠替换反斜杠

python - 使用 re 从文本文件制作字典

python - 在 Bokeh HoverTool 中格式化 Pandas 日期时间

python - 在请求错误回调中处理新项目

python - 删除单词开头的标点符号(特殊符号除外)

javascript - 在两个单词之间应用正则表达式

正则表达式捕获 : word {word} word