C# 正则表达式匹配不包含某个字符串的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1318279/
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
C# Regex to match a string that doesn't contain a certain string?
提问by Shaul Behr
I want to match any string that does notcontain the string "DontMatchThis".
我想匹配任何不包含字符串“DontMatchThis”的字符串。
What's the regex?
什么是正则表达式?
采纳答案by Kamarey
try this:
尝试这个:
^(?!.*DontMatchThis).*$
回答by Wiktor Stribi?ew
The regex to match a string that does not contain a certain pattern is
匹配不包含特定模式的字符串的正则表达式是
(?s)^(?!.*DontMatchThis).*$
If you use the pattern without the (?s)
(which is an inline version of the RegexOptions.Singleline
flag that makes .
match a newline LF symbol as well as all other characters), the DontMatchThis
will only be searched for on the first line, and only a string without LF symbols will be matched with .*
.
如果您使用不带 the 的模式(?s)
(这是匹配换行符 LF 符号以及所有其他字符的RegexOptions.Singleline
标志的内联版本.
),DontMatchThis
则将仅在第一行搜索,并且仅会搜索没有 LF 符号的字符串与.*
.
Pattern details:
图案详情:
(?s)
- a DOTALL/Singleline modifier making.
match any character^
- start of string anchor(?!.*DontMatchThis)
- a negative lookaheadchecking if there are any 0 or more characters (matched with greedy.*
subpattern - NOTEa lazy.*?
version (matching as few characters as possible before the next subpattern match) might get the job done quicker ifDontMatchThis
is expected closer to the string start) followed withDontMatchThis
.*
- any zero or more characters, as many as possible, up to$
- the end of string (see Anchor Characters: Dollar ($
)).
(?s)
- 一个 DOTALL/Singleline 修饰符.
匹配任何字符^
- 字符串锚点的开始(?!.*DontMatchThis)
-一个负先行检查,如果有任何0或更多字符(贪婪匹配的.*
子模式-注意一个懒惰的.*?
版本(匹配为下一子模式比赛前几个字符可能)会完成这项工作更快,如果DontMatchThis
预计接近字符串的开始) 紧随其后DontMatchThis
.*
- 任何零个或多个字符,尽可能多,最多$
- 字符串的结尾(请参阅锚字符:Dollar ($
))。