开发者

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开发者_JAVA技巧 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


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");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜