Use Wildcard (*) with RegEx in VBA to match anything

时间:2019-04-17 01:28:58

标签: regex excel vba

I'm trying to use Regex to match any character (This is just a piece of code from a larger project). I got the below to work, but seems like it is wrong, is there a proper way to search for any character via RegEx?

strPattern = "([!@#$%^&*()]?[a-z]?[0-9]?)"

Eg: MCVE

Public Sub RegExSearch()
    Dim regexp As Object
    Dim rng As Range, rcell As Range
    Dim strInput As String, strPattern As String

    Set regexp = CreateObject("vbscript.regexp")
    Set rng = ActiveSheet.Range("A1:A1")

    With regexp 
    .Global = False 
    .MultiLine = False 
    .ignoreCase = True 
    .Pattern = strPattern 
    End With

    For Each rcell In rng.Cells

        strPattern = "([!@#$%^&*()]?[a-z]?[0-9]?)" ' This matches everything, but seems improper

        If strPattern <> "" Then
            strInput = rcell.Value

            If regexp.test(strInput) Then
                MsgBox rcell & " Matched in Cell" & rcell.Address
            End If
        End If
    Next
End Sub

1 个答案:

答案 0 :(得分:3)

. "Wildcard." The unescaped period matches any character, except a new line. 

strPattern = "."

Or as @RonRosenfeld pointed out, if you need to match everything INCLUDING a "new line" then this would work.

strPattern = "[/S/s]*" 

https://wellsr.com/vba/2018/excel/vba-regex-regular-expressions-guide/