Assume a template syntax where you can use {x}, {{x}}, and {{{x}}}. How can we leverage regular expressions for this?
Example snippet:
{b} c {{d}} e {{{f}}} g
const contents = '{b} c {{d}} e {{{f}}} g';
const tokens = contents.split(/((?<!\\)\{{1,3}(?!\{)|(?<!\}|\\)\}{1,3})/);This will result in:
[
' ', '{', 'b',
'}', ' c ', '{{',
'd', '}}', ' e ',
'{{{', 'f', '}}}',
' g'
]We can now interpret the tokens, which is necessary, because we need to match open and close sets.
(?(DEFINE)(?P<VAR>{[^{}]+})(?P<VAR2>(?&VAR)|{(?&VAR2)}))(?&VAR2)
PS This regular expression only works in engines based on PCRE, see https://www.rexegg.com/regex-recursion.html.