简明Excel VBA(四)正则表达式(Regular Expr

2018-12-08  本文已影响0人  Bluetata

简明Excel VBA

本文集同步于GitHub仓库:# Youchien/concise-excel-vba

1.7 正则表达式(Regular Expression)

在VBA中使用正则表达式,因为正则表达式不是vba自有的对象,
故此要用它就必须采用两种方式引用它:一种是前期绑定,另外一种是后期绑定。

前期绑定:就是手工勾选工具/引用中的Microsoft VBScript Regular Expressions 5.5;
然后在代码中定义对象:Dim regExp As New RegExp;</br>
后期绑定:使用CreateObject方法定义对象:CreateObject("vbscript.regexp")

RegExp对象的属性:

RegExp对象的方法:

Sample Code(前期绑定):

Private Function IsStringDate(ByVal strDate As String)
    Dim strDatePattern
    ' 前期绑定
    Dim regEx As New RegExp, matches

    Dim str MatchContent As String

    strDatePattern = "^(([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4}$"

    With regEx
        .Global = True      ' 搜索字符串中的全部字符,如果为假,则找到匹配的字符就停止搜索!
        .MultiLine = False  ' 是否指定多行搜索
        .IgnoreCase = True  ' 指定大小写敏感(True)
        .Pattern = strDatePattern   ' 所匹配的正则
    End With

    If regEx.Test(strDate) Then     ' 如果与正则相匹配
        Set matches = regEx.Execute(strDate)
        MatchContent = matches(0).Value
    Else
        MatchContent = "Not Matched"
    End If

    IsStringDate = regEx.Test(strDate)

End Function

Sample Code(后期绑定):

Function ExtractNumber(str As String) As String
    Dim regEx As Object
    Set regEx = CreateObject("vbscript.regexp")  ' 后期绑定
    With regEx
        .Global = True       ' 搜索字符串中的全部字符,如果为假,则找到匹配的字符就停止搜索!
        .Pattern = "\D"      ' 非数字字符的正则表达式
        ExtractNumber = .Replace(str, "")        ' 把非数字字符替换成空字符串
    End With
    Set regEx = Nothing      ' 清除内存中的对象变量的地址,即释放内存。
End Function
上一篇 下一篇

猜你喜欢

热点阅读