如何创建JavaScript正则表达式以获取匹配{{match}}

时间:2019-03-10 06:00:46

标签: javascript regex

我想创建获取所有匹配项的JavaScript正则表达式

  {{match1}}{{match2}} notmatch {{match3}}

结果将是

['{{match1}}','{{match2}}','{{match3}}']

到目前为止我尝试了什么

 var text='{{match1}}{{match2}} notmatch {{match3}}';
 const regex = /(?<=\{{)(.*?)(?=\}})/gm;
 var match = text.match(regex);

这在chrome上工作正常,但是在Firefox,IE和Edge中,我遇到此错误

SCRIPT5018: Unexpected quantifier

任何解决方案。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用更简化的正则表达式,如下所示:
(不确定IE,但它应该适用于Chrome和Firefox。)

var text='{{match1}}{{match2}} notmatch {{match3}}';
const regex = /{{([^}]+)}}/gm;
var match = text.match(regex);
console.log(match);

不带括号 :(从here借来的),(Barmar的建议)。

var text='{{match1}}{{match2}} notmatch {{match3}}';
var regex = /{{([^}]+)}}/gm;
var matches;
while (matches = regex.exec(text)){
    console.log(matches[1]);
}