RegEx告诉字符串是不是特定的字符串

问题描述 投票:1回答:3

假设我想匹配除一个以外的所有字符串:“ABC”我该怎么做?

我需要这个用于asp.net mvc 3中的regular expression model validation

regex regex-negation
3个回答
1
投票

通常你会喜欢

(?!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一个实现它们。


1
投票

在不知道你正在使用什么语言的情况下很难回答这个问题,因为有许多正则表达式,但是你可以用负面的预测来做到这一点。

https://stackoverflow.com/a/164419/1112402


0
投票

(?!ABC)^ $ 试试这个,这将排除包含ABC的所有字符串。

© www.soinside.com 2019 - 2024. All rights reserved.