javascript - 从特定格式的字符串中获取变量列表
问题描述
我有一个复杂的字符串,它可以具有特定格式的变量,因为/##{[^}{\(\)\[\]\-\+\*\/]+?}##/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']
解决方案
根据您的模式,因为##
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));
推荐阅读
- python-3.x - 比较两个列表,一个带有通配符,并返回一个包含其差异的新列表
- c# - 从数据库绑定 SelectedValue 时,GridView 的下拉菜单出错?
- mysql - 在搜索和替换查询中使用 IN 和 LIKE
- git - git:为什么主分支中的操作会影响我的私有分支
- php - 当我单击下拉菜单中的内部链接时,整个菜单将关闭,并且不允许我选择内部链接
- scala - 在scala中使用案例类导入csv
- javascript - 打字稿 - 无法拼接数组
- c# - 如何在 ios 项目的 Xamarin.Forms 编辑器中添加显示/隐藏密码图像。(滚动和 UI 放置问题)
- javascript - 对 Javascript 的“.keyCode 属性”的当前状态感到困惑
- javascript - ChartJS - 如何增加 x 轴上标签旋转的最大度数?