30

How can I create a regex NOT to match something? For example I want to regex to match everything that is NOT the string "www.petroules.com".

I tried [^www\.petroules\.com] but that didn't seem to work.

Jake Petroules
  • 23,472
  • 35
  • 144
  • 225

2 Answers2

61
^(?!www\.petroules\.com$).*$

will match any string other than www.petroules.com. This is called negative lookahead.

[^www\.petroules\.com]

means "Match one character except w, p, e, t, r, o, u, l, s or dot".

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 2
    Just what I needed, thanks. Will accept in ~10 minutes as you submitted the first correct answer. – Jake Petroules Jun 03 '10 at 16:16
  • `.*$` is a noop and can be omitted. – Wayne Conrad Jun 03 '10 at 16:46
  • OK, but of course then the match result will be an empty string (with a successful match). If you're just checking whether a match is possible, then this doesn't matter. So yes, omit the `.*$`, and you're done faster. – Tim Pietzcker Jun 03 '10 at 17:02
  • good point. I wasn't considering the match result. So, `.*$` *might* be a noop, or might not, depending. – Wayne Conrad Jun 03 '10 at 18:29
  • @Wayne, in this particular case the regex will only ever match the entire input string or nothing at all, so there is no real reason to actually match the string because you already know what the match is going to be. In other cases, of course, the actual match might matter. – Tim Pietzcker Jun 03 '10 at 18:41
25
(?!...)

This is called negative lookahead. It will only match if the regex ... does not match. However, note that it DOES NOT consume characters. This means that if you add anything else past the ), it will start matching right away, even characters that were part of the negative lookahead.

Donald Miner
  • 38,889
  • 8
  • 95
  • 118