python - 正则表达式用于匹配不具有相同单词出现在另一个关键字之前的关键字

标签 python regex

我需要找到“test”一词何时出现,后跟“follow”,中间没有另一个“test”。

示例:

test
word
word
word
test
test
word
word
follow
word
word
test

我只想要这个:

test
word
word
word
test
**test**
**word**
**word**
**follow**
word
word
test

不过,我对正则表达式不够熟悉,无法做到这一点。任何建议都会很棒。

编辑 虽然单词 test 会在其中多次出现,但单词 follow 只会在字符串中出现一次。

最佳答案

您需要正则表达式才能使用 lookahead在这里。

test(?:\w|\s(?!test))+?follow

(?:) 是非捕获组。 \w 匹配任何单词字符 [a-zA-Z0-9_]\s 匹配任何空格(包括换行符)。 \s(?!test) 仅匹配后面没有 test 的换行符(在正则表达式中称为负向先行)。 ()+? 只是使匹配非贪婪。

通过匹配测试输入:

test
word
**test**
**word**
**follow**
word
test
**test**
**word**
**word**
**follow**
word
word
**test**
**word**
**follow**

<小时/> 以下正则表达式也消除了任何子字符串匹配(例如测试中的测试、抗议等)。

(?<!\w)(test)\s(?!\1\s)(?:\w|\s(?!\1\s))*?(?<!\w)follow(?!\w)

关于python - 正则表达式用于匹配不具有相同单词出现在另一个关键字之前的关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19184192/

相关文章:

python - 这行是什么意思

python - 快速搜索两个列表中的所有元素

python - 转置后如何转置合并相同的列名?

python - 匹配一个单词,后跟任意顺序的两个可选组

javascript - 将正则表达式应用于 javascript 中的 uri 变量

python - 用Python解析模糊时间戳

regex - 谁有把 RegExp 翻译成 "natural language"的算法?

Python 加快从极大字符串中检索数据的速度

c# - 在 C# 中用正则表达式替换 "new line"字符

python - 有什么办法可以让我获得有关 Python 中 AttributeError 异常的具体细节吗?