首页 > 解决方案 > 如果某个单词之前的两个单词来自否定列表,如何使用正则表达式不匹配模式

问题描述

考虑下面的字符串:

str = "word1 word2 word3 word4 word5"

如果 word4 是来自 [sample1, sample2] 的样本并且 word2 不是来自 (sample3, sample4) 的样本,我想匹配一个模式。

例子:

str1 =  "word1 word2 word3 sample1 word5"   # it matches
str2 =  "word1 sample3 word3 sample1 word5"  # it doesn't match

我使用“Negative Lookbehind”编写了一个正则表达式,但我只能匹配一个单词之前而不是两个单词。

谢谢,如果有人可以帮忙。

标签: pythonregexstring

解决方案


我想你正在寻找这样的正则表达式:

\w+ \w+(?<!sample3|sample4) \w+ (?:sample1|sample2) \w+

如果您遇到“固定模式长度”的一些问题,您可以通过这种方式使用负前瞻而不是后

\w+ (?!sample3|sample4)\w+ \w+ (?:sample1|sample2) \w+

因为在前瞻中没有限制。

见正则表达式演示


推荐阅读