Splitting String in VBA using RegEx

自作多情 提交于 2019-11-27 05:22:06

To split a string with a regular expression in VBA:

Public Function SplitRe(Text As String, Pattern As String, Optional IgnoreCase As Boolean) As String()
    Static re As Object

    If re Is Nothing Then
        Set re = CreateObject("VBScript.RegExp")
        re.Global = True
        re.MultiLine = True
    End If

    re.IgnoreCase = IgnoreCase
    re.Pattern = Pattern
    SplitRe = Strings.Split(re.Replace(text, ChrW(-1)), ChrW(-1))
End Function

Usage example:

Dim v
v = SplitRe("a,b/c;d", "[,;/]")

Quoting an example from the documentation of VbScript Regexp: https://msdn.microsoft.com/en-us/library/y27d2s18%28v=vs.84%29.aspx

Function SubMatchTest(inpStr)
    Dim retStr
    Dim oRe, oMatch, oMatches
    Set oRe = New RegExp
    ' Look for an e-mail address (not a perfect RegExp)
    oRe.Pattern = "(\w+)@(\w+)\.(\w+)"
    ' Get the Matches collection
    Set oMatches = oRe.Execute(inpStr)
    ' Get the first item in the Matches collection
    Set oMatch = oMatches(0)
    ' Create the results string.
    ' The Match object is the entire match - dragon@xyzzy.com
    retStr = "Email address is: " & oMatch & vbNewLine
    ' Get the sub-matched parts of the address.
    retStr = retStr & "Email alias is: " & oMatch.SubMatches(0)  ' dragon
    retStr = retStr & vbNewLine
    retStr = retStr & "Organization is: " & oMatch.SubMatches(1)    ' xyzzy
    SubMatchTest = retStr
End Function

To test, call:

MsgBox(SubMatchTest("Please send mail to dragon@xyzzy.com. Thanks!"))

In short, you need your Pattern to match the various parts you want to extract, with the spearators in between, maybe something like:

"(\d+)[/-,](\d+)[/-,](\d+)"

The whole thing will be in oMatch, while the numbers (\d) will end up in oMatch.SubMatches(0) to oMatch.SubMatches(2).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!