(十五)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
相关推荐
埃博拉酱2 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code
唐宋元明清21883 天前
.NET 本地Db数据库-技术方案选型
windows·c#
郑州光合科技余经理3 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1233 天前
matlab画图工具
开发语言·matlab
加号33 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
dustcell.3 天前
haproxy七层代理
java·开发语言·前端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
tryCbest3 天前
Windows环境下配置pip镜像源
windows·pip
呉師傅3 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑