Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Not matching a list of words

Tags:

c#

regex

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

like image 367
LDJ Avatar asked Dec 17 '22 13:12

LDJ


1 Answers

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

like image 171
stema Avatar answered Feb 18 '23 17:02

stema