So I looked at How to write a recursive regex that matches nested parentheses? and other solutions for recursive regex matching, but I'm still not getting a proper match on RegexBuddy.
I have a generic handlebars-style template that I want to parse myself, a table with headings:
<table>
<thead>
<tr>
{{#each columns as col }}<th>{{col}}</th>{{/each}}
</tr>
</thead>
<tbody>
{{#each rows as row }}
<tr>
{{#each row as col }}<td>col</td>{{/each}}
</tr>
{{/each}}
</tbody>
</table>
And trying to match with
/{{\#each (\w+) as (\w+) }}(.*?|(?R)){{/each}}/s
The regex matches the {{#each columns...
in the <thead>
just fine, but it seems to ignore the |(?R)
part and matches {{#each rows...
only until the first {{/each}}
. I, of course, would like it to match both the inner and outer #each
expressions. How? This is perhaps much more complex than simple nested parentheses.
(I always feel like I'm a pro at RegEx until I run into things like this. I have been trying for a while to make this work, and regular-expressions.info is just confusing me more.)
I'm currently working around this by doing {{#each_sub...}}...{{/each_sub}}
so my regex won't stop on the first closing tag, but that's obviously a sub-optimal way of doing it. I have several other applications that would benefit from recursive regex but can't figure out what I'm doing wrong.