Regex - match anything except specific string

自古美人都是妖i 提交于 2019-12-18 04:04:28

问题


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.

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").

Any ideas of how to fix the regex?


回答1:


You can include the end of string anchor in the lookahead

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



回答2:


Perhaps this regex can help you out:

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

Check out this at Rubular.




回答3:


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

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


来源:https://stackoverflow.com/questions/16930563/regex-match-anything-except-specific-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!