I'm looking to apply a regular expression to an input string to make sure it doesn’t match a list of predefined values. For example, if I pass in the word Dog, I don’t want it to match. Likewise for Cat. However, if I pass in Sheep, it should match. I’ve tried:
^(?!(Dog)|(Cat))$ << Doesn’t match Dog, Cat or sheep!
^((?!Dog)|(?!Cat))$ << Doesn’t match Dog, Cat or sheep!
^(?!Dog|Cat)$ << Doesn’t match Dog, Cat or sheep!
^(?!Dog)|(?!Cat)$ << matches everything because Dog != Cat for example
Basically, if I pass in "Dogs", it should match as dog != dogs. But if I pass in exactly dog or cat then it should not match.
I thought this would be really easy, but I'm puling my hair out! Thanks
The lookahead assertions doesn't match anything. after closing it you need to match the characters, so try e.g.
^(?!.*Dog)(?!.*cat).*$
See it here at Regexr
They are described here in detail on msdn
If you want to match those words exactly then use word boundaries like this
^(?!.*\bDog\b)(?!.*\bCat\b).*$
Regexr
The \b
ensures that there is no word character before or following
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