How to include variable in Regular expression pattern

前端 未结 2 1821
失恋的感觉
失恋的感觉 2020-12-11 23:37

I am working on a vba macro which uses regular expression to search for a string pattern in another string.

Regex pattern includes a string (APR24 in code below) wh

2条回答
  •  时光说笑
    2020-12-12 00:01

    You can specify whatever pattern you want in str2srch and then assign that to Regex.Pattern

    For example

    Sub Sample()
        Debug.Print Regexsrch("APR24ffffd", "APR24")  '<~~ Returns True
        Debug.Print Regexsrch("APR277ffffd", "APR24") '<~~ Returns False
    End Sub
    
    Public Function Regexsrch(ByVal str2bsrchd As String, ByVal str2srch As String) As Boolean
        Dim Regex As New VBScript_RegExp_55.RegExp
        Dim matches, s
    
        Regex.Pattern = str2srch
        Regex.IgnoreCase = True
    
        If Regex.Test(str2bsrchd) Then
             Regexsrch = True
        Else
            Regexsrch = False
        End If
    End Function
    

    FOLLOWUP

    Even if it is dynamic you can always pass the pattern as

    Debug.Print Regexsrch("APR24ffffd", "(\.|\s)" & VARIABLE & "(,|\s|\()").

    This gives you the flexibility of using whatever pattern you want to pass to the function and you are not limited to one pattern...

提交回复
热议问题