Quad
Quad

Reputation: 1718

Regex match array notation

I am trying to find array-like occurrences in a string.

For instance for this text

Ut ac nisi eget est tempus mattis. Sed et dapibus lorem. Suspendisse laoreet ante arcu, sed ornare a(diam)[test] ornare eget. Nunc a(pulvinar)[anoter][test] porttitor accumsan. Donec quis accumsan enim.Ut sed sem posuere, a(pharetra)[another[nested][a(test)]] sapien a, molestie odio. Donec euismod, lectus et sollicitudin condimentum, felis dolor feugiat arcu

i want to match bold parts.

i got this far:

\a\((.*?)\)(\[.*?])+

this matches first two, but the last test has the last closing bracket missing.(If i nest once more 2 closing brackets becomes missing)

results:

a(diam)[test]
a(pulvinar)[anoter][test]
a(pharetra)[another[nested][a(test)] <--- last closing bracket missing.

any help?

Upvotes: 1

Views: 467

Answers (1)

Kita
Kita

Reputation: 2634

How about embedding the nested structure in regular expression like this:

a\(\w+\)(\[.+?(\[.+\])*\])+
              ---------  
              embeded nesting

EDIT:

(a\(\w+\)(?:\[.+?(?:\[.+\])*\])+)

Added non-capturing symbols to mitigate "undefined" captures.

Upvotes: 1

Related Questions