VBA 中正则表达式使用指南

发布于:2025-03-31 ⋅ 阅读:(21) ⋅ 点赞:(0)

1. 正则表达式基础用法

1.1 引入正则表达式

  • 前期绑定:工具 → 引用 → Microsoft VBScript Regular Expressions 5.5
    Dim regex As New RegExp
    
  • 后期绑定
    Set regex = CreateObject("VBScript.RegExp")
    

1.2 常用属性设置

regex.Global = True  ' 全局搜索(默认False,只匹配第一个)
regex.Pattern = "表达式内容"  ' 设置正则表达式
regex.IgnoreCase = True  ' 忽略大小写(默认False)

1.3 基本操作方法

Set k = regex.Execute(目标字符串)  ' 执行匹配,返回MatchCollection对象
n = regex.Replace(目标字符串, 替换字符串)  ' 替换操作

1.4 With语句简化

With regex
    .Global = True
    .Pattern = "正则表达式"
    .Replace "", ""
    .Execute 目标字符串
End With

2. 正则表达式元字符

元字符 说明
\d 匹配数字
. 匹配除换行符外的任意字符
? 匹配前导字符0次或1次
+ 匹配前导字符1次或多次
* 匹配前导字符0次或多次
{n,m} 匹配前导字符n到m次
() 分组捕获
[] 字符集合
` `

3. 高级技巧

3.1 分组与引用

.Pattern = "(\d{4})-(\d{2})-(\d{2})"  ' 分组匹配日期
' 使用$1,$2,$3引用分组

3.2 非捕获分组

.Pattern = "(?:\d{4})"  ' 使用?:表示非捕获分组

3.3 Test方法

If regex.Test(目标字符串) Then
    ' 匹配成功执行的代码
End If

3.4 SubMatches用法(捕获分组值)

Sub 捕获分组值()
    Set regx = CreateObject("VBScript.RegExp")
    With regx
        .Global = True
        .Pattern = "(\w{3,}) (\d+)"
        Set mat = .Execute([A1])
        For Each m In mat
            n = n + 1
            Cells(n + 1, 3) = .Replace(m.Value, "$1")  ' 第一分组
            Cells(n + 1, 4) = .Replace(m.Value, "$2")  ' 第二分组
        Next
    End With
End Sub

4. 常用正则表达式示例

  1. 整数匹配

    • 正整数:^[0-9]*[1-9][0-9]*$
    • 整数:^-?\d+$
  2. 浮点数匹配

    • 正浮点数:^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$
  3. 邮箱匹配

    • ^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
  4. URL匹配

    • ^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$
  5. 中文匹配

    • [\u4e00-\u9fa5]
  6. 电话号码

    • ^(\d{3,4}-)?\d{7,8}$
  7. IP地址

    • ^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$
  8. 日期匹配

    • ^\d{4}-\d{1,2}-\d{1,2}$

5. 实用示例代码

5.1 首尾锚定示例

Sub test()
    Set regx = CreateObject("VBScript.RegExp")
    With regx
        .Global = True
        .Pattern = "^[A-Z]+\d+$"
        For Each Rng In [A1:A17]
            Set mat = .Execute(Rng)
            For Each m In mat
                n = n + 1
                Cells(n, 2) = m
            Next
        Next
    End With
End Sub

5.2 循环正则表达式

' 将正则表达式放到数组中循环
Dim patterns(2)
patterns(0) = "\d+"
patterns(1) = "[A-Z]+"
patterns(2) = "[\u4e00-\u9fa5]+"

For Each p In patterns
    regex.Pattern = p
    ' 执行匹配操作
Next

以上内容总结了VBA中使用正则表达式的主要知识点和实用技巧,可作为日常开发参考。