Skip to content

Instantly share code, notes, and snippets.

@timoschinkel
Last active September 22, 2023 07:08
Show Gist options
  • Save timoschinkel/73e61becb15a301f302df90ae72ebf59 to your computer and use it in GitHub Desktop.
Save timoschinkel/73e61becb15a301f302df90ae72ebf59 to your computer and use it in GitHub Desktop.
Accolade matching regular expressions

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

Option 1 - using JavaScript

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.

Option 2 - using recursive regular expressions

(?(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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment