javascript regexp匹配" {"和"}"但不是" @ {"和"}"

时间:2015-11-19 04:12:59

标签: javascript regex

例如两个字符串:"1@{loop1}dummy{s1}dummy""{loop1}dmy{s1}dmy", 我的表达式是:/[^@]\{([\S\s][^\}@]*)\}/g 我在https://regex101.com/r/tN8iH6/1

测试了它

匹配" s1"在第一个字符串中," loop1"," s1"在第二个字符串中,这正是我需要的, 但是当你在javascript中编写代码时:

var str1 = "1@{loop1}dummy{s1}dummy";
var str2 = "{loop1}dmy{s1}dmy";
var reg = /[^@]\{([\S\s][^\}@]*)\}/g
function getRegMatchedStrs(reg,str){
    rs = [];
    var regRs = 1;
    while(regRs){
        regRs = reg.exec(str);
        regRs && rs.push(regRs[1]);
    }
    return rs;
}

console.log(getRegMatchedStrs(reg,str1)); // get ["s1"] as expected
console.log(getRegMatchedStrs(reg,str2)); // get ["s1"] unexpected has no "loop1"

谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

您在大括号之前匹配非@字符,因此大括号不能位于字符串的开头。将[^@]更改为(?:^|[^@])(字符串开头或非@)。

编辑:这无法解决无法匹配bar"{foo}{bar}"的问题。男人,没有后卫真的很糟糕。这是两个解决方法:

var str1 = "1@{loop1}dummy{s1}dummy";
var str2 = "{loop1}dmy{s1}dmy";
var str3 = "{loop1}{s1}dmy";

var reg1 = /{(.+?)}/g
function getRegMatchedStrs1(reg, str) {
    var rs = [];
    var regRs = true;
    while ((regRs = reg.exec(str))) {
        if (!regRs.index || str.charAt(regRs.index - 1) !== '@') {
            rs.push(regRs[1]);
        }
    }
    return rs;
}
console.log(JSON.stringify(getRegMatchedStrs1(reg1, str1)));
console.log(JSON.stringify(getRegMatchedStrs1(reg1, str2)));
console.log(JSON.stringify(getRegMatchedStrs1(reg1, str3)));
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

var str1 = "1@{loop1}dummy{s1}dummy";
var str2 = "{loop1}dmy{s1}dmy";
var str3 = "{loop1}{s1}dmy";

var reg2 = /}(.+?){(?!@)/g
function getRegMatchedStrs2(reg, str) {
    var rs = [];
    var regRs = true;
    str = str.split('').reverse().join('');
    while ((regRs = reg.exec(str))) {
        rs.push(regRs[1].split('').reverse().join(''));
    }
    return rs;
}
console.log(JSON.stringify(getRegMatchedStrs2(reg2, str1)));
console.log(JSON.stringify(getRegMatchedStrs2(reg2, str2)));
console.log(JSON.stringify(getRegMatchedStrs2(reg2, str3)));
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>