C# Regex to match a string that doesn't contain a certain string?

99封情书 提交于 2020-01-09 13:11:06

问题


I want to match any string that does not contain the string "DontMatchThis".

What's the regex?


回答1:


try this:

^(?!.*DontMatchThis).*$



回答2:


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 .*.

Pattern details:

  • (?s) - a DOTALL/Singleline modifier making . match any character
  • ^ - start of string anchor
  • (?!.*DontMatchThis) - a negative lookahead checking if there are any 0 or more characters (matched with greedy .* subpattern - NOTE a lazy .*? version (matching as few characters as possible before the next subpattern match) might get the job done quicker if DontMatchThis is expected closer to the string start) followed with DontMatchThis
  • .* - any zero or more characters, as many as possible, up to
  • $ - the end of string (see Anchor Characters: Dollar ($)).


来源:https://stackoverflow.com/questions/1318279/c-sharp-regex-to-match-a-string-that-doesnt-contain-a-certain-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!