Search code examples
regexpreg-matchregex-negation

Regex - match anything except specific string


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?


Solution

  • You can include the end of string anchor in the lookahead

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