3

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?

John Jiang
  • 11,069
  • 12
  • 51
  • 60

1 Answers1

4

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.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306