Regex - match anything except specific string

rafaame picture rafaame · Jun 5, 2013 · Viewed 39.7k times · Source

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?

Answer

Explosion Pills picture Explosion Pills · Jun 5, 2013

You can include the end of string anchor in the lookahead

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