Regex for string not containing multiple specific words

后端 未结 2 1305
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 03:23

I\'m trying to put together a regex to find when specific words don\'t exist in a string. Specifically, I want to know when \"trunk\", \"tags\" or \"branches\" does

相关标签:
2条回答
  • 2020-12-01 03:59

    Use a negative look-ahead that asserts the absence of any of the three words somewhere in the input:

    ^(?!.*(trunk|tags|branches)).*$
    

    I also slightly rearranged your regex to correct minor errors.

    0 讨论(0)
  • 2020-12-01 04:12

    Use a "standard" match and look for !IsMatch

    var exp = new Regex(@"trunk|tags|branches");
    var result = !exp.IsMatch("trunk/blah/blah");
    

    Why persons love to make their life difficult?

    Ah... And remember the ass principle! http://www.codinghorror.com/blog/2008/10/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea.html

    So it would be better to write

    var exp = new Regex(@"\b(trunk|tags|branches)\b");
    

    But if you really need a negative lookahed expression, and keeping up with the ass principle

    var exp = new Regex(@"^(?!.*\b(trunk|tags|branches)\b)";
    

    Tester: http://gskinner.com/RegExr/?2uv1g

    I'll note that if you are looking for full paths (words separated by / or \) then

    var exp = new Regex(@"^(?!.*(^|\\|/)(trunk|tags|branches)(/|\\|$))";
    

    Tester: http://gskinner.com/RegExr/?2uv1p

    0 讨论(0)
提交回复
热议问题