VBA custom regular expression

A custom function for regular expressions

How to use: Insert a module, paste in the above code, quote "Microsoft VBScript Regular Expressions 5.5" in the tool and it will be OK.

Order Name Representation
1 Group ( )
2 In groups ? + * {m,n} {m, n}?
3 Anchor point abc ^ $
4 or
5 Take group $0-$9
Character table:
Apr same as meaning
\d [0-9] digital
\D [ ^0-9] Not a number
\w [a-zA-Z0-9_] Numbers and letters
\W [^ a-zA-Z0-9_] Non-numeric letters
\s [ \r\t\f] blank
\S [ ^ \r\t\f] Non-blank
[\n] New line

A few examples:

=regex(“Peter Gordon: [email protected], 47”, “\w+@\w+.\w+”)

=regex(“Peter Gordon: [email protected], 47”, “\w+@\w+.\w+”, “$0”)

Results in: [email protected]

=regex(“Peter Gordon: [email protected], 47”, “^(.+): (.+), (\d+)$”, “E-Mail: $2, Name: $1”)

Results in: E-Mail: [email protected], Name: Peter Gordon

=regex(“Peter Gordon: [email protected], 47”, “^(.+): (.+), (\d+) " , " ", " ","” & 1)

=regex(“Peter Gordon: [email protected], 47”, “^(.+): (.+), (\d+) " , " ", " ","” & 2)

Results in: Peter Gordon [email protected] .

Code:

Function regex(strInput As String, matchPattern As String, Optional ByVal outputPattern As String = "$0") As Variant
    Dim inputRegexObj As New VBScript_RegExp_55.RegExp, outputRegexObj As New VBScript_RegExp_55.RegExp, outReplaceRegexObj As New VBScript_RegExp_55.RegExp
    Dim inputMatches As Object, replaceMatches As Object, replaceMatch As Object
    Dim replaceNumber As Integer

    With inputRegexObj
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = matchPattern
    End With
    With outputRegexObj
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = "\$(\d+)"
    End With
    With outReplaceRegexObj
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
    End With

    Set inputMatches = inputRegexObj.Execute(strInput)
    If inputMatches.count = 0 Then
        regex = False
    Else
        Set replaceMatches = outputRegexObj.Execute(outputPattern)
        For Each replaceMatch In replaceMatches
            replaceNumber = replaceMatch.SubMatches(0)
            outReplaceRegexObj.Pattern = "\$" & replaceNumber

            If replaceNumber = 0 Then
                outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).Value)
            Else
                If replaceNumber > inputMatches(0).SubMatches.count Then
                    'regex = "A to high $ tag found. Largest allowed is $" & inputMatches(0).SubMatches.Count & "."
                    regex = CVErr(xlErrValue)
                    Exit Function
                Else
                    outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).SubMatches(replaceNumber - 1))
                End If
            End If
        Next
        regex = outputPattern
    End If
End Function

Guess you like

Origin blog.csdn.net/rankiy/article/details/103390043