首页 > 解决方案 > 在 VBA 中使用通配符 (*) 和正则表达式来匹配任何内容

问题描述

我正在尝试使用正则表达式来匹配任何字符(这只是来自更大项目的一段代码)。我得到了下面的工作,但似乎它是错误的,有没有通过正则表达式搜索任何字符的正确方法?

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

例如: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

标签: regexexcelvba

解决方案


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

strPattern = "."

或者正如@RonRosenfeld 指出的那样,如果您需要匹配包括“新行”在内的所有内容,那么这将起作用。

strPattern = "[/S/s]*" 

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


推荐阅读