I've this regex
{{([ a-zA-Z0-9_\-]+)\s*(?:\[([ a-zA-Z0-9_\-]+)\]\s*)*}}
and i need to match strings such as:
{{word with spaces}}
{{word with spaces [sub1]}}
{{word with spaces [sub1] [sub 2] [Sub-3] }}
capturing word with spaces
, and sub1
, sub 2
, Sub-3
.
The regex is working but the for the sub-s string matching gives only the last match, i.e. Sub-3
. How to get all sub1
, sub 2
, Sub-3
? Thanks
Here is another variant using \G
that is bit faster and avoids empty matches:
(?:{{([\w-]+(?:\h+[\w-]+)*)|(?!\A)\G)(?:\h*\[([^]]+)]|\h*}})
\G
asserts position at the end of the previous match or the start of the string for the first match.
To get the value for sub in mulitple times group 2 you might use \G
to assert the position at the end of the previous match:
(?:{{([\w-]+(?: [\w-]+)*)|\G(?!$))(?:\h+\[([^]]+)\])?(?=.*})