简体   繁体   中英

javascript regexp match anything between “{” and “}”,but not between “@{” and “}”

two strings as example: "1@{loop1}dummy{s1}dummy" and "{loop1}dmy{s1}dmy" , my reg expression is: /[^@]\\{([\\S\\s][^\\}@]*)\\}/g I tested it at: https://regex101.com/r/tN8iH6/1

it matched "s1" in first string,"loop1","s1" in second string, this is exactly what i need, but when code this in 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"

thank you for your help!

You are matching a non- @ character before the braces, so the braces can't be at the start of the string. Change [^@] to (?:^|[^@]) (start of string or non- @ ).

EDIT: This does not solve the problem of being unable to match bar in "{foo}{bar}" . Man, not having lookbehind really sucks. Here's two workarounds:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM