【发布时间】:2012-03-13 14:22:03
【问题描述】:
假设我想匹配除一个之外的所有字符串:“ABC” 我该怎么做?
我在 asp.net mvc 3 中需要 regular expression model validation。
【问题讨论】:
标签: regex regex-negation
假设我想匹配除一个之外的所有字符串:“ABC” 我该怎么做?
我在 asp.net mvc 3 中需要 regular expression model validation。
【问题讨论】:
标签: regex regex-negation
通常你会喜欢
(?!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 的字符串。
【讨论】:
希望这会有所帮助:
^(?!^ABC$).*$
使用这个表达式,您将获得从 (^) 开始到 ($) 结束之间所有可能的字符串 (.*),但那些恰好是 ^ABC$.
【讨论】: