我试图在遵循类似{{any thing here}}
这样的特定模式的字符串中找到所有匹配项,但是我无法正确提取所有匹配项。不知道我在做什么错。下面是到目前为止我尝试过的代码。
const string = `You have been identified in <span class="alert underline">{{db.count}}</span> breaches with <span class="alert underline">{{db.data_types}}</span> unique data types.`;
我尝试了以下方法:
方法1
const matches = /{{(.*?)}}/igm.exec(value);
console.log(matches);
输出:
{
0: "{{db.count}}",
1: "db.count",
index: 58,
input: "You have been identified in <span class="alert und…line">{{db.data_types}}</span> unique data types.",
groups: undefined
}
方法2
const matches = RegExp('{{(.*?)}}', 'igm').exec(value);
console.log(matches);
输出:
{
0: "{{db.count}}",
1: "db.count",
index: 58,
input: "You have been identified in <span class="alert und…line">{{db.data_types}}</span> unique data types.",
groups: undefined
}
方法3
const matches = value.match(/{{(.*?)}}/igm);
console.log(matches);
输出:
[
"{{db.count}}",
"{{db.data_types}}"
]
预期输出:
[
'db.count',
'db.data_types'
]
如果有人遇到过同样的问题,请提供帮助。 预先感谢。
答案 0 :(得分:2)
如果要查找所有匹配项,则必须循环使用exec()。
示例:
const string = `You have been identified in <span class="alert underline">{{db.count}}</span> breaches with <span class="alert underline">{{db.data_types}}</span> unique data types.`;
let regEx = /{{(.*?)}}/igm;
let result;
while ((result = regEx.exec(string)) !== null) {
console.log(result[1]);
}
答案 1 :(得分:0)
您的方法3看起来不错。我会尝试使用此正则表达式来匹配花括号:
[^{}]+(?=}})
答案 2 :(得分:0)
/ g(全局)标志See here不能很好地进行分组。 @fragezeichen提供了正确的解决方案(也记录在链接中)