- vba正则表达式的说明
项目 | 说明 |
---|---|
Pattern | 在这里写正则表达式,例:[\d]{2,4} |
IgnoreCase | 大小写区分,默认false:区分;true:不区分 |
Global | true:全体检索;false:最小匹配 |
Test | 类似perl正则前的m,匹配项目 |
Replace | 类似perl正则前的s,替换项目 |
Execute | 类似java的matcher,然后能取出里边的group1,group2,group3;或者perl里匹配的各个括号的值 |
※正则表达式怎么写,这里不做说明,我是做perl的时候看了那本骆驼书然后顿悟的,以前特别怕写正则,现在还挺喜欢写的,特别是用正则解决了问题后
2.Test的用法
vbnet
Sub test()
Dim RE As String
Dim patt As String
Set RE = CreateObject("VBScript.RegExp")
pattern = "[0-9]{2,4}"
With RE
.pattern = patt
.IgnoreCase = True
.Global = True
If .test("word1234aa") Then
Debug.Print "11111"
Else
Debug.Print "22222"
End If
If .test("word4aa") Then
Debug.Print "33333"
Else
Debug.Print "44444"
End If
End With
Set RE = Nothing
End Sub
执行结果:
原因:没有引正则的包
很遗憾,macos vba无法使用正则,因为没有正则的引用
但是上边我写的正则匹配应该是没问题的
3.Replace的用法
vbnet
Sub test()
Dim RE As String
Set RE = CreateObject("VBScript.RegExp")
With RE
.pattern = "[0-9]{2,4}"
.IgnoreCase = False
.Global = True
End With
Dim str As String, ret As String
str = "I love you 123"
ret = RE.Replace(str, "zy")
Debug.Print ret
Set RE = Nothing
'输出结果:I love you zy
End Sub
4.Execute的用法
vbnet
Sub test()
Dim RE, patt As String, pmatch
Set RE = CreateObject("VBScript.RegExp")
patt = "I love ([\d]+) and ([\d]+)"
With RE
.pattern = patt
.IgnoreCase = True
.Global = True
Set pmatch = .Execute("I love 123 and 456")
If pmatch.Count > 0 Then
Debug.Print pmatch(0) & "======" & pmatch(1)
End If
End With
Set pmatch = Nothing
Set RE = Nothing
End Sub