4

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) which varies. I need to know how to include a variable in the pattern.Could any one please help.

My code is as below

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 = "(\.|\s)APR24(,|\s|\()"
Regex.IgnoreCase = True
    If Regex.Test(str2bsrchd) Then
         Regexsrch = True
Else
        Regexsrch = False
End If
End Function

2 Answers 2

5

So str2srch is "APR24" or some variation? If that is the case you just use concatenation to build up your pattern string.

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 = "(\.|\s)" + str2srch + "(,|\s|\()"
Regex.IgnoreCase = True
    If Regex.Test(str2bsrchd) Then
         Regexsrch = True
Else
        Regexsrch = False
End If
End Function
Sign up to request clarification or add additional context in comments.

1 Comment

The regex can be improved by using character classes, eg, Regex.Pattern = "[.\s]" + str2srch + "[,\s(]"
1

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

For example

Sub Sample()
    Debug.Print Regexsrch("APR24ddd", "APR24")  '<~~ Returns True
    Debug.Print Regexsrch("APR277ddd", "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("APR24ddd", "(\.|\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...

2 Comments

See followup in the post above
@Downvoter: I don't mind the downvote but at least have the decency to leave a comment as to why you feel a downvote is required? Or is the too much to ask for?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.