Reputation: 9355
I have a complex string which can have variable in specific format as /##{[^}{\(\)\[\]\-\+\*\/]+?}##/g
I want to extract those variables in an array.
e.g.
var x= "sgsegsg##{xx}gerweg##{xx1}##rgewrgwgwrg}##ferwfwer##{xx2}rgrg##{xx3}####{xx4}####{errg}}}";
function getVariableNames (param) {
return param.match(/(##{[^}{\(\)\[\]\-\+\*\/]+?}##)+?/g)
}
getVariableNames(x);
above lines returns ["##{xx1}##", "##{xx3}##", "##{xx4}##"]
where I want to get ['xx1', 'xx3', 'xx4']
Upvotes: 1
Views: 56
Reputation: 9355
I tried it with following and it worked:
var x= "sgsegsg##{xx}gerweg##{xx1}##rgewrgwgwrg}##ferwfwer##{xx2}rgrg##{xx3}####{xx4}####{errg}##{xx5(}####{xx-6}####{xx7}##}}";
function getVariableNames (str) {
let variables = str.match(/(##{[^}{)(\]\[\-+*\/]+?}##)+?/g);
return variables && variables.length ? variables.map(i=>i.substring(3, i.length - 3)) : false;
}
getVariableNames(x)
Upvotes: 0
Reputation: 370979
Based on your pattern, because the portion inside the ##
s won't contain curly braces, simply repeating non-curly braces is enough: [^}]+
. Match the repeated non-bracket characters, and then iterate through the matches and extract the captured group:
const str = "sgsegsg##{xx}gerweg##{xx1}##rgewrgwgwrg}##ferwfwer##{xx2}rgrg##{xx3}####{xx4}####{errg}}}";
const pattern = /##{([^}]+)}##/g;
let match;
const matches = [];
while (match = pattern.exec(str)) {
matches.push(match[1]);
}
console.log(matches);
On newer environments, you can lookbehind for ##{
instead:
const str = "sgsegsg##{xx}gerweg##{xx1}##rgewrgwgwrg}##ferwfwer##{xx2}rgrg##{xx3}####{xx4}####{errg}}}";
const pattern = /(?<=##{)[^}]+(?=}##)/g;
console.log(str.match(pattern));
Upvotes: 2