简体   繁体   中英

How to get multiple strings between two other strings

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM