15

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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
rafaame
  • 822
  • 2
  • 12
  • 22

3 Answers3

10

You can include the end of string anchor in the lookahead

 ^(?!(red|blue|green)$)
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
2

Perhaps this regex can help you out:

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

Check out this at Rubular.

NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
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

'(?si)(?!.*(red|green|blue).*)(.*(YOUR_REGEXP).*)'
Dante
  • 279
  • 1
  • 19