我正在尝试阻止" ^ $ /()|?+ [] {}><"元字符 有人给我一些有关为什么这样做的见解。 我是新手:/(TextBox3是一个输入的asp文本框)
Imports System.Text.RegularExpressions
Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If Regex.IsMatch(TextBox3.Text, "^$\/()|?+[]{}><") Then
Label1.Text = "Invalid input"
End If
End Sub
End Class
ERROR:
Exception Details: System.ArgumentException: parsing "^$\/()|?+[]{}><" - Unterminated [] set.
答案 0 :(得分:0)
那是因为字符串^$\/()|?+[]{}><
是正则表达式元字符。在传递给regex函数之前,你需要转义它们:
If Regex.IsMatch(TextBox3.Text, Regex.Escape("^$\/()|?+[]{}><")) Then
Label1.Text = "Invalid input"
End If
更新的答案:
检查文本是否包含任何正则表达式元字符的2种方法:
方法1:使用正则表达式
元字符需要放在字符类[...]
中。因此,只需要转义部分字符,即:^
,\
和]
。
If Regex.IsMatch(TextBox1.Text, "[\^$\\/()|?+[\]{}><]") Then
' Invalid input
Else
' Valid
End If
方法2:使用IndexOfAny
字符串函数
此方法不使用正则表达式,因此无需转义。
If TextBox1.Text.IndexOfAny("^$\/()|?+[]{}><".ToCharArray) > -1 Then
' Invalid input
Else
' Valid
End If