Regex - 匹配除特定字符串之外的任何内容

时间:2021-03-09 20:12:48

I need a regex (will be used in ZF2 routing, I believe it uses the preg_match of php) that matches anything except a specific string.

我需要一个正则表达式(将在ZF2路由中使用,我相信它使用php的preg_match)匹配除特定字符串之外的任何内容。

For example: I need to match anything except "red", "green" or "blue".

例如:我需要匹配除“红色”,“绿色”或“蓝色”之外的任何内容。

I currently have the regex:

我目前有正则表达式:

^(?!red|green|blue).*$

test -> match (correct)
testred -> match (correct)
red -> doesn't match (correct)
redtest -> doesn't match (incorrect)

In the last case, the regex is not behaving like I want. It should match "redtest" because "redtest" is not ("red", "green" or "blue").

在最后一种情况下,正则表达式的行为并不像我想要的那样。它应匹配“redtest”,因为“redtest”不是(“red”,“green”或“blue”)。

Any ideas of how to fix the regex?

有关如何修复正则表达式的任何想法?

3 个解决方案

#1


11  

You can include the end of string anchor in the lookahead

您可以在前瞻中包含字符串锚点的结尾

 ^(?!(red|blue|green)$)

#2


2  

Perhaps this regex can help you out:

也许这个正则表达式可以帮助你:

^(?!red|green|blue)(.+)|(.+)(?<!red|green|blue)$

Check out this at Rubular.

在Rubular看看这个。

#3


0  

Regexp like this includes condition of second block - YOUR_REGEXP, and exclude condition of first block. In this case if your string will contains red, green or blue result always would be false

像这样的正则表达式包括第二个块的条件 - YOUR_REGEXP,并排除第一个块的条件。在这种情况下,如果您的字符串将包含红色,绿色或蓝色结果,则始终为false

'(?si)(?!.*(red|green|blue).*)(.*(YOUR_REGEXP).*)'

#1


11  

You can include the end of string anchor in the lookahead

您可以在前瞻中包含字符串锚点的结尾

 ^(?!(red|blue|green)$)

#2


2  

Perhaps this regex can help you out:

也许这个正则表达式可以帮助你:

^(?!red|green|blue)(.+)|(.+)(?<!red|green|blue)$

Check out this at Rubular.

在Rubular看看这个。

#3


0  

Regexp like this includes condition of second block - YOUR_REGEXP, and exclude condition of first block. In this case if your string will contains red, green or blue result always would be false

像这样的正则表达式包括第二个块的条件 - YOUR_REGEXP,并排除第一个块的条件。在这种情况下,如果您的字符串将包含红色,绿色或蓝色结果,则始终为false

'(?si)(?!.*(red|green|blue).*)(.*(YOUR_REGEXP).*)'