LDJ
LDJ

Reputation: 7304

Regex: Not matching a list of words

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

Upvotes: 6

Views: 20228

Answers (2)

Pooli
Pooli

Reputation: 503

Assuming (albeit bravely) that I've understood the question, I believe that the issue here is in the use zero width expressions, and the case sensitivity of the strings you are looking to search for.

I think that what you need is listed below.

void Main()
{
    string test = "sheep";

    var regEx = new Regex("^([dD][oO][gG]|[cC][aA][tT])$");

    Console.WriteLine(regEx.IsMatch(test) ? "Found" : "Not Found");
}

Alternatively, you could do this without regex as follows

void Main()
{
    List<string> excludeStrings = new List<string> { "dog", "cat" };

    string inputString = "Dog";

    Console.WriteLine(excludeStrings.Contains(inputString, StringComparer.CurrentCultureIgnoreCase) ? "Found" : "Not Found");
}

Upvotes: 0

stema
stema

Reputation: 92986

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

Upvotes: 16

Related Questions