(十五)VBA常用基础知识:正则表达式的使用

  1. 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
相关推荐
NignSah1 分钟前
Microsoft Excel World Championship 2025-2025EXCEL大赛,折纸
microsoft·excel
提笔忘字的帝国2 分钟前
【2026版】macOS 使用 Homebrew 快速安装 Java 21 教程
java·开发语言·macos
半壶清水2 分钟前
【开源免费】使用 Python + Whisper + PyDub 自动切割长音频文件
开发语言·python·语言模型·开源·whisper
ghostwritten2 分钟前
go.mod 与go.sum有什么区别?
开发语言·后端·golang
hhzz4 分钟前
Springboot项目中使用POI操作Excel(详细教程系列1/3)
spring boot·后端·excel·poi·easypoi
抹香鲸之海7 分钟前
Easyexcel 多级横向合并表头
java·开发语言·windows
林月明8 分钟前
【VBA】点击一个按钮实现自动更新excel文件列数据
excel·vba·宏文件·一键数据更新
superman超哥8 分钟前
Rust 生命周期子类型:类型系统中的偏序关系
开发语言·后端·rust·编程语言·rust生命周期·偏序关系
雒珣9 分钟前
qt界面和图片疯狂变大的bug问题
开发语言·qt·bug
BD_Marathon11 分钟前
SpringMVC——bean加载控制
java·开发语言·数据库