Skuli
Skuli

Reputation: 2067

RegEx to tell if a string is not a specific string

Suppose I want to match all strings except one: "ABC" How can I do this?

I need this for a regular expression model validation in asp.net mvc 3.

Upvotes: 1

Views: 229

Answers (4)

Iván
Iván

Reputation: 1

Hope this can help:

^(?!^ABC$).*$

With this expression you're going to get all possible strings (.*) between beginning (^) and the end ($) but those that are exactly ^ABC$.

Upvotes: 0

H S Umer farooq
H S Umer farooq

Reputation: 1081

(?!.*ABC)^.*$

This will exclude all strings which contains ABC.

Upvotes: 0

xanatos
xanatos

Reputation: 111910

Normally you would do like

(?!ABC)

So for example:

^(?!ABC$).*

All the strings that aren't ABC

Decomposed it means:

^ beginning of the string
(?!ABC$) not ABC followed by end-of-string
.* all the characters of the string (not necessary to terminate it with $ because it is an eager quantifier)

Technically you could do something like

^.*(?<!^ABC)$

Decomposed it means

^ beginning of the string
.* all the characters of the string 
(?<!^ABC) last three characters captured aren't beginning-of-the-string and ABC 
$ end of the string (necessary otherwise the Regex could capture `AB` of `ABC` and be successfull)

using a negative look behind, but it is more complex to read (and to write)

Ah and clearly not all the regex implementations implement them :-) .NET one does.

Upvotes: 1

gorjusborg
gorjusborg

Reputation: 656

It's hard to answer this definitively without knowing what language you are using, since there are many flavors of regular expressions, but you can do this with negative lookahead.

https://stackoverflow.com/a/164419/1112402

Upvotes: 1

Related Questions