我在经典ASP中使用正则表达式进行验证。我想验证两个不同的值,并检查是否只有两个模式中提到的列出的字符和符号用于该值,并且我尝试使用两个不同的Regex对象。但这对我不起作用
我的代码
Set re = New RegExp
With re
.Pattern = "[a-zA-Z0-9&_+()/-]"
.Global = True
.IgnoreCase = True
End With
Set reNew = New RegExp
With reNew
.Pattern = "[a-zA-Z0-9.!"£$%^&()_+-=[]{}#:@./<>?\|]"
.Global = True
.IgnoreCase = True
End With
if re.Test(strComments) = false then
response.write " <label>Upload failed !! Please enter comments using valid characters a-z A-Z 0-9 ._+()%/&-</label>"
response.end
else
if reNew.Test(strremark) = false then
response.write "<label> Upload failed !! Please enter remark using valid characters a-z A-Z 0-9 ._+()%/&-</label>"
response.end
end if
end if
谁能告诉我我在哪里出错了?
用以下代码修复:
Set re = New RegExp
With re
.Pattern = "^[a-zA-Z0-9&_+()/-]+$"
End With
Set reNew = New RegExp
With reNew
.Pattern = "^[a-zA-Z0-9.!""£$%^&()_+=[]{}#:@./<>?\|-]+$"
End With
双引号必须为双引号,连字符必须用作括号内的最后字符,并且右括号也必须转义。
&
有一个不必要的反斜杠,我删除了。
锚点用于匹配整个字符串,+
确保匹配一个或多个允许的字符。
不要设置.Global = True
和.IgnoreCase = True
,这是多余的代码,因为它们都可以是False
。
不需要多个RegExp
对象实例,唯一改变的是模式,它只是一个字符串,所以将字符串存储在一个变量中,并在每个Test()
之前替换模式。
Dim stringToTest: stringToTest = "..." 'Your test string
Dim validationPattern1: validationPattern1 = "..."
Dim validationPattern2: validationPattern2 = "..."
Dim re: Set re = New RegExp
'Set regex properties
With re
.Gloabl = True
.IgnoreCase = True
End With
'Before testing add the pattern
re.Pattern = validationPattern1
If Not re.Test(stringtoTest) Then
'Validation1 failure logic here
'...
End If
'Add the next pattern
re.Pattern = validationPattern2
If Not re.Test(stringtoTest) Then
'Validation2 failure logic here
'...
End If