I want to create an expression parser (in javascript but also examples in other languages welcomed) to grab values inside the ${ } tag.
So in the case of ${ foo bar } i want to extract "foo bar"
Thanks in advance!
CodePudding user response:
This works in typescript.
var exp = (/(?<=\${)(.*?)(?=})/g);
console.log("${foo bar} ${test 1} no test ${test 2}".match(exp));
Output
[LOG]: ["foo bar", "test 1", "test 2"]
CodePudding user response:
You can use regex to achieve this simply like this
text = '${ foo bar }';
regex = /\$\s*{\s*(.*)}/g;
matchedText = text.match(regex)[1].trim();
console.log(matchedText);
- Regex is a tool to find patterns in a string.
- The variable
regex
stores that pattern in this program. - Then we try to find the substring part of the
text
that matches the pattern described inregex
. text.match(regex)
returns an array containing the entire matched substring and then the specific value that you're looking for in${ foo bar }
which isfoo bar
. Therefore we access the element on the1
index, strip it and then store it inmatchedText
.