VBA使用正则表达式

通过菜单 工具 -> 引用 引用了Microsoft VBScript Regular Expressions 5.5 后就可以声明正则相关对象。主要有三个对象:RegExp、MatchCollection、Match。

示例代码:

Sub Test()
    Dim re As RegExp
    Dim mh As Match
    Dim mhs As MatchCollection
    Dim inpStr As String
    
    inpStr = "我的E-mail: me@lishewen.com 。"
    Set re = New RegExp
    re.Pattern = "(w+)@(w+).(w+)"
    Set mhs = re.Execute(inpStr)
    Set mh = mhs(0)                                      '只有一个匹配
    
    MsgBox "电子邮件地址是: " & mh.Value          '这里是匹配的内容
    MsgBox "用户名是:       " & mh.SubMatches(0)  '第一个括号中的内容
    MsgBox "邮箱是:         " & mh.SubMatches(1)  '第二个括号中的内容
    MsgBox "域名是:       " & mh.SubMatches(2)  '第三个括号中的内容    
End Sub
不允许评论