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.
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.
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
(?!.ABC)^.$
try this, this will exclude all strings which contains ABC.
上一篇: 匹配没有两个单词的行