Skip to content

Instantly share code, notes, and snippets.

@EddieDemon
Created July 29, 2016 09:52
Show Gist options
  • Save EddieDemon/0690b2b95af77f14f852c45f51373f74 to your computer and use it in GitHub Desktop.
Save EddieDemon/0690b2b95af77f14f852c45f51373f74 to your computer and use it in GitHub Desktop.
Regex to get value between two curly brackets. Safe for three curly brackets.

Regex Snippet - {{placeholder}}

Parsing double-curly-bracket-enclosed-placeholders

I felt the need for double-curly-bracket-enclosed-placeholders for translation purposes. I didn't want to use single-brackets. (Used to Angular, sorry. ;))

It's actually quite simple what it does: Check for double curly-brackets, and make sure that after it, there's no curly bracket.

The Regex

\{\{(?!{)(.*?)\}\}

Credits for the single-bracket method, on which this was enhanced: Paul Dixon

I'm not really sure, but depending on the "executing language" you could remove the backslahes ("\") before the curely-brackets.

Explaned

  • \{ matches the character { literally
  • \{ matches the character { literally
  • (?!{) Negative Lookahead - Assert that it is impossible to match the regex below
    • { matches the character { literally
  • 1st Capturing group (.*?)
    • .*? matches any character (except newline)
      • Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
  • \} matches the character } literally
  • \} matches the character } literally

Explaination format by: Regex101

Exmaple

This is a {{arg1}}. It has been created by: {{name}} on {{date}}. Note: {{{note}}}

This will create four groups:

  • {{arg1}}
  • {{name}}
  • {{date}}
  • {{note}}

These can now be replaced using your favourite language. The result will be something like this:

This is a test. It has been created by: Eddie on 2016-07-29. Note: {Yes, even this works!}

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