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?
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 '.
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.
The ?! n quantifier matches any string that is not followed by a specific string n.
You can include the end of string anchor in the lookahead
^(?!(red|blue|green)$)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With