我有一个复杂的字符串,它可以包含特定格式的变量,如/##{[^}{\(\)\[\]\-\+\*\/]+?}##/g,我想将这些变量提取到一个数组中。
例如:
var x= "sgsegsg##{xx}gerweg##{xx1}##rgewrgwgwrg}##ferwfwer##{xx2}rgrg##{xx3}####{xx4}####{errg}}}";
function getVariableNames (param) {
return param.match(/(##{[^}{\(\)\[\]\-\+\*\/]+?}##)+?/g)
}
getVariableNames(x); 上面的行返回["##{xx1}##", "##{xx3}##", "##{xx4}##"]
我想在哪里找到['xx1', 'xx3', 'xx4']
发布于 2019-04-28 14:40:19
根据您的模式,因为##s中的部分不包含大括号,所以只需重复非大括号就足够了:[^}]+。匹配重复的非括号字符,然后遍历匹配并提取捕获的组:
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);
在较新的环境中,您可以改为查找##{:
const str = "sgsegsg##{xx}gerweg##{xx1}##rgewrgwgwrg}##ferwfwer##{xx2}rgrg##{xx3}####{xx4}####{errg}}}";
const pattern = /(?<=##{)[^}]+(?=}##)/g;
console.log(str.match(pattern));
https://stackoverflow.com/questions/55887648
复制相似问题