1

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.

Skuli
  • 1,859
  • 2
  • 20
  • 28

4 Answers4

1

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.

xanatos
  • 106,283
  • 12
  • 188
  • 265
1

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

Community
  • 1
  • 1
gorjusborg
  • 646
  • 4
  • 18
0
(?!.*ABC)^.*$

This will exclude all strings which contains ABC.

Wai Ha Lee
  • 8,173
  • 68
  • 59
  • 86
H S Umer farooq
  • 871
  • 8
  • 14
0

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

Kevin M. Mansour
  • 1,932
  • 5
  • 14
  • 28
Iván
  • 1