vba regex wildcard code example

Example: vba regex wildcard

' Returns true if pSearched matches pPattern with wildcards
' Needs reference "Microsoft VBScript Regular Expressions 5.5"
Function RegexMatch(ByVal pSearched As String, ByVal pPattern As String, _
    Optional ByVal pIgnoreCase As Boolean = True) As Boolean
    Dim rRegex As Object
    
    Set rRegex = CreateObject("VBScript.RegExp")
    pPattern = Replace(pPattern, ".", "[.]")
    pPattern = Replace(pPattern, "*", ".*")
    pPattern = Replace(pPattern, "?", ".")
    With rRegex
        .IgnoreCase = pIgnoreCase
        .Pattern = pPattern
    End With
    RegexMatch = rRegex.test(pSearched)
End Function
' ------------------------------------------------------------------------
Sub TestMe()
    Debug.Print RegexMatch("helloworld.txt", "*.txt")            'True
    Debug.Print RegexMatch("helloworld.txt", "hell*o?ld.tx*")    'True
    Debug.Print RegexMatch("HELLOworld.txt", "hel*.tx*", False)  'False
End Sub

Tags:

Vb Example