【发布时间】:2016-01-26 01:24:45
【问题描述】:
让我们在下面的文字中说
I want [this]. I want [this too]. I don't want \[this]
我想要[] 但不是\[] 之间的任何内容。我该怎么做呢?到目前为止,我有/\[([^\]]+)\]/gi。但它匹配一切。
【问题讨论】:
标签: javascript regex parsing
让我们在下面的文字中说
I want [this]. I want [this too]. I don't want \[this]
我想要[] 但不是\[] 之间的任何内容。我该怎么做呢?到目前为止,我有/\[([^\]]+)\]/gi。但它匹配一切。
【问题讨论】:
标签: javascript regex parsing
使用这个:/(?:^|[^\\])\[(.*?)\]/gi
这是一个工作示例:http://regexr.com/3clja
?:非捕获组^|[^\\] 字符串开头或除@987654325之外的任何内容@
\[(.*?)\] 匹配 [] 之间的任何内容
这是一个sn-p:
var string = "[this i want]I want [this]. I want [this too]. I don't want \\[no]";
var regex = /(?:^|[^\\])\[(.*?)\]/gi;
var match = null;
document.write(string + "<br/><br/><b>Matches</b>:<br/> ");
while(match = regex.exec(string)){
document.write(match[1] + "<br/>");
}
【讨论】:
使用这个正则表达式,它首先匹配 \[] 版本(但不捕获它,从而“将其丢弃”),然后是 [] 案例,捕获里面的内容:
var r = /\\\[.*?\]|\[(.*?)\]/g;
^^^^^^^^^ MATCH \[this]
^^^^^^^^^ MATCH [this]
与exec 循环以获取所有匹配项:
while(match = r.exec(str)){
console.log(match[1]);
}
【讨论】:
/(?:[^\\]|^)\[([^\]]*)/g
内容在第一个捕获组,$1
(?:^|[^\\]) 匹配行的开头或任何不是斜线的内容,非捕获。
\[ 匹配左括号。
([^\]]*) 捕获任意数量的非右括号的连续字符
\] 匹配右括号
【讨论】: