Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 492
rafaame Avatar asked Jun 05 '13 02:06

rafaame


People also ask

How do you exclude a word in regex?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '.

What is the regular expression is used to match any single character except character?

Match any specific character in a set Use square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

What is ?! In regex?

The ?! n quantifier matches any string that is not followed by a specific string n.


1 Answers

You can include the end of string anchor in the lookahead

 ^(?!(red|blue|green)$)
like image 111
Explosion Pills Avatar answered Sep 21 '22 12:09

Explosion Pills