Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: Submatching regex

Tags:

regex

vba

I have the following code:

Dim results(1) As String
Dim RE As Object, REMatches As Object
Set RE = CreateObject("vbscript.regexp")

With RE
    .MultiLine = False
    .Global = True
    .IgnoreCase = True
    .Pattern = "(.*?)(\[(.*)\])?"
End With

Set REMatches = RE.Execute(str)

results(0) = REMatches(0).submatches(0)
results(1) = REMatches(0).submatches(2)

Basically if I pass in a string "Test" I want it to return an array where the first element is Test and the second element is blank.

If I pass in a string "Test [bar]", the first element should be "Test " and the second element should be "bar".

I can't seem to find any issues with my regex. What am I doing wrong?

like image 833
John Jiang Avatar asked Oct 14 '25 03:10

John Jiang


1 Answers

You need to add beginning and end of string anchors to your regex:

...
.Pattern = "^(.*?)(\[(.*)\])?$"
...

Without these anchors, the .*? will always match zero characters and since your group is optional it will never try to backtrack and match more.

like image 66
Andrew Clark Avatar answered Oct 17 '25 06:10

Andrew Clark