.net 不包含多个特定单词的字符串的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7801581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex for string not containing multiple specific words
提问by Troy Hunt
I'm trying to put together a regex to find when specific words don'texist in a string. Specifically, I want to know when "trunk", "tags" or "branches" doesn't exist (this is for a Subversion pre-commit hook). Based on the Regular expression to match string not containing a wordanswer I can easily do this for one word using negative look-arounds:
我正在尝试组合一个正则表达式来查找字符串中何时不存在特定单词。具体来说,我想知道什么时候“主干”、“标签”或“分支”不存在(这是针对 Subversion 预提交钩子的)。基于匹配不包含单词答案的字符串的正则表达式,我可以使用否定查找轻松地对一个单词执行此操作:
^((?!trunk).)*$
It's the "and" operator I'm struggling with and I can't seem to get combinations including the other two words working.
这是我正在努力使用的“and”运算符,我似乎无法获得包括其他两个词在内的组合。
This is running fine in .NET with a single word:
这在 .NET 中运行良好,只需一个词:
var exp = new Regex(@"^((?!trunk).)*$");
exp.IsMatch("trunk/blah/blah");
It will return false as it currently stands or true if "trunk" doesn't exist in the path on the second line.
如果第二行的路径中不存在“trunk”,它将返回当前状态的 false 或 true。
What am I missing here?
我在这里缺少什么?
回答by Bohemian
Use a negative look-aheadthat 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.
我还稍微重新排列了您的正则表达式以纠正小错误。
回答by xanatos
Use a "standard" match and look for !IsMatch
使用“标准”匹配并寻找 !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 assprinciple! 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 assprinciple
但是如果你真的需要一个否定的lookahed表达,并且跟上ass原则
var exp = new Regex(@"^(?!.*\b(trunk|tags|branches)\b)";
Tester: http://gskinner.com/RegExr/?2uv1g
测试员: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)(/|\|$))";

