This question already has answers here:
RegEx to extract all matches from string using RegExp.exec
                                
                                    (18个回答)
                                
                        
                                在11个月前关闭。
            
                    
我试图在遵循这样的特定模式的字符串中找到所有匹配项,例如{{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'
]


如果有人遇到过同样的问题,请提供帮助。
提前致谢。

最佳答案

如果要查找所有匹配项,则必须在循环中使用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]);
}

08-05 19:55