如何否定正则表达式?

时间:2018-05-09 17:51:07

标签: .net regex vb.net

我正在检查分配给变量s的字符串,到目前为止我有这个:

If Regex.IsMatch(s, "[\d]+") Then something
If Regex.IsMatch(s, "[A-Z]+") Then something
If Regex.IsMatch(s, "[a-z]+") Then something
If Regex.IsMatch(s, "[$%&*_=+^]+") Then something
If Regex.IsMatch(s, "^([\d]|[A-Z]|[a-z]|[$%&*-_=+^])") Then something

问题在于我的最后一句话。我想说,如果你有一个数字,大写,小写或我允许的符号之外的任何东西,那么做一些事情。我试图使用否定^但它不起作用。 每个if语句都设置一个计数器,因此这不是if,否则是场景

2 个答案:

答案 0 :(得分:1)

您可以使用布尔值来跟踪每次检查的进度。

Dim matches = False
If Regex.IsMatch(s, "[\d]+") Then matches = True
If Regex.IsMatch(s, "[A-Z]+") Then matches = True
If Regex.IsMatch(s, "[a-z]+") Then matches = True
If Regex.IsMatch(s, "[$%&*_=+^]+") Then matches = True
If Not matches Then something

然后,如果要在其中执行其他操作,只需将每个语句更改为多行语法,而不仅仅是检查它们是否匹配。

答案 1 :(得分:0)

您不需要否定它,只需对所有这些案例使用ElseIf,然后使用Else作为最后一个案例:

If Regex.IsMatch(s, "[\d]+") Then
    'something
ElseIf Regex.IsMatch(s, "[A-Z]+") Then
    'something
ElseIf Regex.IsMatch(s, "[a-z]+") Then
    'something
ElseIf Regex.IsMatch(s, "[$%&*_=+^]+") Then
    'something
Else
    'something
End If