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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With