33

Possible Duplicate:
Regular expression to match string not containing a word?
How can I invert a regular expression in JavaScript?

Say I have the regex foo123. How do I match everything that is not foo123?

Community
  • 1
  • 1
StackOverflowNewbie
  • 39,403
  • 111
  • 277
  • 441

1 Answers1

28

Use negative lookahead for this.

(?!foo123).+

matches any string except foo123

If you want to match empty string also, use (?!foo123).*

In your case (according to the comment) the required regex is (?!P[0-9]{1,}).+.

It matches P and 123, but not P123.

Naveed S
  • 5,106
  • 4
  • 34
  • 52
  • 2
    This is not going to work if you are searching in a file (none of them will work correctly when searching, but this is probably not what the OP wants). The first regex is also wrong for validation. – nhahtdh Feb 04 '13 at 10:14
  • 2
    @nhahtdh how is it wrong? – Naveed S Feb 04 '13 at 10:38
  • 1
    I shouldn't have downvoted you since the question itself is confusing. Anyway, for matching: `(?!foo123).+` and `(?!foo123).*` http://www.regex101.com/r/gC0xA6 Add `^` and `$` for validation http://www.regex101.com/r/pS3zM5 Checking that the whole string does not follow the pattern can be done by using negation to result of match function instead of negating inside the regex – nhahtdh Feb 04 '13 at 10:47
  • @nhahtdh So you mean `foo123khsdkfh` should not be matched and `afoo123khsdkfh` should be matched? – Naveed S Feb 04 '13 at 11:49
  • Since the OP is not very clear on what he wants (there are a number of ways to interpret the question), my downvote was a bit uncalled for (as I mentioned in my earlier comment). If you edit your answer a bit and clarify that the regex (surrounded with `^` and `$`) can only be used to validate that the whole string doesn't match the pattern, then I will remove the downvote. – nhahtdh Feb 04 '13 at 12:01
  • 4
    I can't get the point in matching `afoo123khsdkfh` but not `foo123khsdkfh` – Naveed S Feb 04 '13 at 12:09
  • 1
    SEARCH: `\b(foo123)\b|.` REPLACE BY: `(?{1}\1)` – Just Me Jul 23 '17 at 18:22
  • @JustMe Didn't get your point. – Naveed S Jul 25 '17 at 06:45
  • match everything in text that is not "foo123" :) Maybe I didn't understand the question?? – Just Me Jul 25 '17 at 21:52
  • @JustMe Why that replace part is there? OP just needs to find everything which is not foo123. – Naveed S Jul 26 '17 at 12:32