(?<=\[)[^\]]*(?=\])
匹配文字:
[11/Sep/2016:21:58:55 +0000]
在测试时它可以在崇高的情况下正常工作,但是当我这样做时
str.match(/(?<=\[)[^\]]*(?=\])/)
我有错误: SyntaxError:无效的正则表达式
我做错了什么?
答案 0 :(得分:1)
您可以将正则表达式用作:/[^\[\]]+/
const regex = /[^\[\]]+/;
const str = `[11/Sep/2016:21:58:55 +0000]`;
let m;
if ((m = regex.exec(str)) !== null) {
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
答案 1 :(得分:1)
您可以使用捕获并抓取第1组内容。
如果要提取一个值,请使用
var m = "[11/Sep/2016:21:58:55 +0000]".match(/\[([^\]]*)]/);
console.log(m ? m[1] : "No match");
如果还有其他内容,请将RegExp#exec
与/\[([^\]]*)]/g
一起使用并收集匹配项:
var s = "[11/Sep/2016:21:58:55 +0000] [12/Oct/2016:20:58:55 +0001]";
var rx = /\[([^\]]*)]/g;
var res = [];
while ((m=rx.exec(s)) !== null) {
res.push(m[1]);
}
console.log(res);