给定一个 Javascript 字符串
{include} anything in {curly braces} but not when they are escaped like {this} and work for any position of the {brace}
我要找回
- 包括
- 大括号
- 大括号
我一直在寻找一种方法,但如果不回头看,我就会陷入困境。
最重要的是不要获取转义的 {} 内容。如果有必要的话,我会同意在比赛中包含大括号的东西。
不幸的是,到目前为止我所做的只是这样的表达
(?:[^//]){.*?}
但是如果 { 位于目标文本的开头,则不匹配。
有人可以帮助我吗?谢谢。
最佳答案
我假设转义字符是/
。
您可以将以下正则表达式与将保存您的值的捕获组一起使用:
/(?:^|[^\/]){([^}]*)}/g
^^^^^^^
请参阅regex demo
详细信息:
(?:^|[^\/])
- 字符串的开头或/
之外的字符{
- 文字{
([^}]*)
- 第 1 组捕获除}
之外的任何 0+ 字符(将{
添加到类中以匹配{
和}
之间的最短窗口)}
- 文字}
。
var rx = /(?:^|[^\/]){([^}]*)}/g;
var str = "{include} anything in {curly braces} but not when they are escaped like /{this} and work for any position of the {brace}";
var m, res = [];
while ((m = rx.exec(str)) !== null) {
res.push(m[1]);
}
console.log(res);
关于Javascript Regex - 仅捕获未转义的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41719460/