且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

匹配不包含所有指定元素的字符串的正则表达式

更新时间:2022-11-30 11:57:33

好问题.看起来您正在寻找一些 AND 逻辑.我相信有人可以想出更好的方法,但我想到了两种方法:

Nice question. It looks like you are looking for some AND logic. I am sure someone can come up with something better, but I thought of two ways:

^(?=(?!.*\btwo\b)|(?!.*\bthree\b)).*$

查看在线演示

或者:

^(?=.*\btwo\b)(?=.*\bthree\b)(*SKIP)(*F)|^.*$

查看在线演示

在这两种情况下,我们都使用正向前瞻来模仿 AND 逻辑,以防止两个词出现在文本中,而不管它们在完整字符串中的位置.如果只存在这些单词中的一个,则字符串将通过.

In both cases we are using positive lookahead to mimic the AND logic to prevent both words being present in a text irrespective of their position in the full string. If just one of those words is present, the string will pass.