首页 > 解决方案 > 从特定格式的字符串中获取变量列表

问题描述

我有一个复杂的字符串,它可以具有特定格式的变量,因为/##{[^}{\(\)\[\]\-\+\*\/]+?}##/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']

标签: javascriptregex

解决方案


根据您的模式,因为##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));


推荐阅读