2

I am trying to find all values between {{ and }} that start with a $ followed by [\w.]+ but doesn't start with a number. This works in getting the value, however, it only gets the last item. What I am looking for, is a list of these items, so in this example I would like my array to contain (based off the example):

['{{I\'m $name and I am $age years old}}', '$name', '$age']

When executed, $name is not included in this array as seen here:

let result = '$welcome: {{I\'m $name and I am $age years old}}'.match(/\{\{.*(\$(?!\d|\.)[\w.]+).*\}\}/)

console.log(result)

2
  • 1
    Try \$[.\w]+(?=[^{}]*}). Or match that block first then run another regex on it. Commented Nov 8, 2018 at 16:56
  • This seems to be working regex101.com/r/GUcHxt/1 Commented Nov 8, 2018 at 17:00

1 Answer 1

1

You could try the below regex:

\$[.\w]+(?=[^{}]*})

Live demo

This doesn't really match between {{ and }} but it guarantees that it wouldn't find a match which is outside of braces. It assumes that single, unbalanced braces do not occur in input string.

Another approach would be matching an entire {{...}} block then looking for \$[\w.]+ but if you need to replace them in original input string this wouldn't be an easy option.

Sign up to request clarification or add additional context in comments.

2 Comments

I am trying your second method, however, /\$(?!(\d|\.))[.\w]+/ is only getting $name and not $age
Oops nope I didn't that fixes it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.