目的:实现像format函数一样分割字符串。例如将字符串"a{bc}d"转换为["a", "bc", "d"],字符串"a{{bc}}d"转换为["a{bc}d"](两个花括号相当于转义)。如果知道如何匹配数量为奇数的花括号,那么分割就有办法了(re.split)。除了正则表达式,我暂时想不到别的办法,如有办法不使用正则表达式也可以提出,优先采纳简单的方法。
匹配要求:
匹配 数量为奇数的左花括号 或 数量为奇数的右花括号(使用非贪心匹配)
正则表达式格式最好为Python(其他语言的正则表达式差别应该也不大)
请给出正则表达式。
例子:
"{abc}"使用findall匹配得到["{", "}"]
"{{abc}}"使用findall无匹配(因为数量为偶数)
"{{{abc}}}"使用findall匹配得到["{", "}"]
感谢回答!
(\{\{)*\{[^\{](\}\})*\}
思路就是匹配0或者多个双括号,后面跟着单括号。
function splitString(s) {
const pattern = /(?<!\{)\{|\}(?!\})/;
const result = s.split(pattern);
return result;
}
const s1 = "a{bc}d";
const s2 = "a{{bc}}d";
const s3 = "{{{abc}}}";
console.log(splitString(s1)); // ["a", "bc", "d"]
console.log(splitString(s2)); // ["a{bc}d"]
console.log(splitString(s3)); // ["{", "}"]