Regular expression to match handlebar expression and default value

Viewed 161

I'm loosely following a handlebar pattern to replace instances of a {{copy}} expression inside a string.

Here are some example of strings/scenarios I'm trying to match:

  • {{copy}}
  • some text, then {{copy}}, then some other other text
  • some {{copy 'default value here'}} here

Essentially {{copy}} can occur anywhere within a string, and can also include a default value which I also need to pluck out using regex.

I've tried the following which I thought would match, but am having no luck.

    \b{{copy*}}\b
2 Answers

You can use this regex:

/{{(copy)\b(?: +'([^']*)')?}}/

Explanation:

  • {{ - expect handlebar start
  • (copy) - capture text copy (replace with [a-z]+ to support variable keywords)
  • \b - expect a word boundary
  • (?: ... )? - non-capturing group, the trailing ? makes it optional
    • +'([^']*)' - expect 1+ spaces, a quote, capture everything after until before next quote, expect quote
  • }} - expect handlebar end
  • now you can reference the capture groups with $1 and $2, or \1 and \2, or array depending on the regex engine/language construct.

You can use

{{copy\s*([^}]*)}}

See the regex demo. Details:

  • {{copy - a literal text
  • \s* - zero or more whitespaces
  • ([^}]*) - Capturing group 1: any zero or more chars other than }
  • }} - a }} string.
Related