const regex = /{\s*{\s*#\s*(?<operator>endcase|endswitch|endfor|endif|if|elif|else|for|switch|case|default)\s*(?<args>[^}]*)\s*}\s*}\s*(?<body>[^{]*(?:\s*{\s*{\s*#\s*(?!(?&operator))\s*[^}]*\s*}\s*}\s*[^{]*)*)/uig;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('{\\s*{\\s*#\\s*(?<operator>endcase|endswitch|endfor|endif|if|elif|else|for|switch|case|default)\\s*(?<args>[^}]*)\\s*}\\s*}\\s*(?<body>[^{]*(?:\\s*{\\s*{\\s*#\\s*(?!(?&operator))\\s*[^}]*\\s*}\\s*}\\s*[^{]*)*)', 'uig')
const str = `<div>
{{#if arg1.arg2}}
<span>{{#var arg3 static}}</span>
blablabla{{#for k, v in arg4}}
<p>{{#var k}}<span>{{#var v.arg5}}</span></p>
{{#if (k == "test" or v != 0) and k == 0}}
<span></span>
{{#elif k == 0}}
<p></p>
{{#else}}
<div></div>
{{#endif}}
{{#endfor}}
{{#endif}}
{{#switch arg6}}
{{#case 5}}
case 5
{{#case 6, 7, 8}}
case 6, 7, 8
{{#endcase}}
{{#default}}
def
{{#endcase}}
{{#endswitch}}
{{#for i as 0, 5}}
test i
{{#endfor}}`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions