Splitting String in VBA using RegEx

前端 未结 2 1635
情书的邮戳
情书的邮戳 2020-11-30 13:20

I\'m new to VBA and would like to seek some help with regards to using RegEx and I hope somehow can enlighten me on what I\'m doing wrong. I\'m currently trying to split a d

相关标签:
2条回答
  • 2020-11-30 13:41

    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", "[,;/]")
    
    0 讨论(0)
  • 2020-11-30 13:44

    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).

    0 讨论(0)
提交回复
热议问题