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,997
  • 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
  • 109,618
  • 12
  • 197
  • 280
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
  • 656
  • 4
  • 18
0
(?!.*ABC)^.*$

This will exclude all strings which contains ABC.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
H S Umer farooq
  • 981
  • 1
  • 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
  • 2,915
  • 6
  • 18
  • 35
Iván
  • 1