我在使用 {} 时遇到了一些问题。当我得到像 {1,8} 这样的最大值时,它不起作用,我现在不知道为什么。最小值有效
Private Sub Highlvl_Expression()
Dim strPattern As String: strPattern = "[a-zA-Z0-9_]{1,8}"
Dim strReplace As String: strReplace = ""
Dim regEx As New RegExp
Dim Test As Boolean
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
Test = regEx.Test(Highlvl.Value)
If regEx.Test(Highlvl.Value) Then
MsgBox ("Validate")
Else
MsgBox ("Not Validate")
End If
End Sub
最佳答案
您指定了在字符串中查找 1 到 8 个字母数字字符的模式。如果您对 9 个字符的字符串运行正则表达式 "ABCDE6789"
( regEx.Execute("ABCDE6789")
),您将有 2 个匹配项:ABCDE678
和 9
.
如果你想验证一个应该有最小或最大字符数的字符串,你需要使用 anchors ,即字符串断言的开始和结束 ^
和 $
.所以,使用
Dim strPattern As String: strPattern = "^[a-zA-Z0-9_]{1,8}$"
和
.Global = False
全局标志不是必需的,因为我们不是在寻找多个匹配项,而是寻找具有
test
的单个真或假结果。 .
关于regex - Visual Basic Excel 正则表达式 {},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31874332/