4

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

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.