Regex - match anything except specific string
Asked Answered
T

3

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?

Thereinafter answered 5/6, 2013 at 2:23 Comment(0)
J
10

You can include the end of string anchor in the lookahead

 ^(?!(red|blue|green)$)
Jodoin answered 5/6, 2013 at 2:35 Comment(3)
This regex is matching nothing. Have you tested it?Thereinafter
@Thereinafter yup; matched test, testred, and redtest, but not red rubular.com/r/b9eMsVln1WJodoin
@Thereinafter perhaps try adding .* at the end if you need to actually capture the stringJodoin
E
2

Perhaps this regex can help you out:

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

Check out this at Rubular.

Enculturation answered 5/6, 2013 at 5:35 Comment(0)
A
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).*)'
Allfired answered 11/9, 2015 at 12:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.