How To Negate Regex [duplicate]
Asked Answered
G

1

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?

Gerda answered 4/2, 2013 at 8:27 Comment(3)
The strings to match can have different lengths?Bedlam
Sure. The actual pattern I'm trying not to match is: ^P[0-9]{1,}$Gerda
Match as in search, or validation? For validation, you can use the same string, but use negation to the result of the matching function.Islas
T
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.

Tavi answered 4/2, 2013 at 8:40 Comment(10)
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.Islas
@Islas how is it wrong?Tavi
I shouldn't have downvoted you since the question itself is confusing. Anyway, for matching: (?!foo123).+ and (?!foo123).* regex101.com/r/gC0xA6 Add ^ and $ for validation 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 regexIslas
@Islas So you mean foo123khsdkfh should not be matched and afoo123khsdkfh should be matched?Tavi
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.Islas
I can't get the point in matching afoo123khsdkfh but not foo123khsdkfhTavi
SEARCH: \b(foo123)\b|. REPLACE BY: (?{1}\1)Stoops
@JustMe Didn't get your point.Tavi
match everything in text that is not "foo123" :) Maybe I didn't understand the question??Stoops
@JustMe Why that replace part is there? OP just needs to find everything which is not foo123.Tavi

© 2022 - 2024 — McMap. All rights reserved.