- 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的用法
Sub test()Dim RE As StringDim patt As StringSet RE = CreateObject("VBScript.RegExp")pattern = "[0-9]{2,4}"With RE.pattern = patt.IgnoreCase = True.Global = TrueIf .test("word1234aa") ThenDebug.Print "11111"ElseDebug.Print "22222"End IfIf .test("word4aa") ThenDebug.Print "33333"ElseDebug.Print "44444"End IfEnd WithSet RE = Nothing
End Sub
执行结果:
原因:没有引正则的包
很遗憾,macos vba无法使用正则,因为没有正则的引用
但是上边我写的正则匹配应该是没问题的
3.Replace的用法
Sub test()Dim RE As StringSet RE = CreateObject("VBScript.RegExp")With RE.pattern = "[0-9]{2,4}".IgnoreCase = False.Global = TrueEnd WithDim str As String, ret As Stringstr = "I love you 123"ret = RE.Replace(str, "zy")Debug.Print retSet RE = Nothing'输出结果:I love you zy
End Sub
4.Execute的用法
Sub test()Dim RE, patt As String, pmatchSet RE = CreateObject("VBScript.RegExp")patt = "I love ([\d]+) and ([\d]+)"With RE.pattern = patt.IgnoreCase = True.Global = TrueSet pmatch = .Execute("I love 123 and 456")If pmatch.Count > 0 ThenDebug.Print pmatch(0) & "======" & pmatch(1)End IfEnd WithSet pmatch = NothingSet RE = Nothing
End Sub