假设我想匹配除一个以外的所有字符串:“ABC”我该怎么做?
我需要这个用于asp.net mvc 3中的regular expression model validation。
通常你会喜欢
(?!ABC)
例如:
^(?!ABC$).*
所有不是ABC
的字符串
分解它意味着:
^ 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)
从技术上讲,你可以做点什么
^.*(?<!^ABC)$
分解它意味着
^ 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)
使用负面外观,但读取(和写入)更复杂
啊,显然不是所有的正则表达式实现都实现了它们:-) .NET一个实现它们。
在不知道你正在使用什么语言的情况下很难回答这个问题,因为有许多正则表达式,但是你可以用负面的预测来做到这一点。
(?!ABC)^ $ 试试这个,这将排除包含ABC的所有字符串。