41

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

What's the regex?

2
  • Why do you want to do this with regex and not use String.IndexOf? Commented Aug 23, 2009 at 10:54
  • 17
    Because sometimes your regex is in config and you can't change the code. Or because you need it as a subexpression of another more complex regex. Or any one of a number of reasons. You might as well ask, "Why don't you get your cat to mime the text to you via the medium of interpretive dance instead?". Sometimes you just don't have your cat to hand. Commented Jan 6, 2015 at 17:55

2 Answers 2

70

try this:

^(?!.*DontMatchThis).*$
Sign up to request clarification or add additional context in comments.

Comments

40

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 ($)).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.