简体   繁体   English

Javascript正则表达式错误,两个字符之间的文本

[英]Javascript regex error, text between two characters

(?<=\[)[^\]]*(?=\])

which is matching text: 匹配文本:

[11/Sep/2016:21:58:55 +0000] 

it works fine in sublime while testing, but when I do 在测试时,它在升华方面效果很好,但是当我这样做时

str.match(/(?<=\[)[^\]]*(?=\])/) 

Ive got error: SyntaxError: Invalid regular expression Ive错误:SyntaxError:正则表达式无效

what Im doing wrong ? 我在做什么错?

You can use regex as : /[^\\[\\]]+/ 您可以将regex用作: / [^ \\ [\\]] + /

 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}`); }); } 

You may use capturing and grab the Group 1 contents. 您可以使用捕获并获取第1组的内容。

If you have one value to extract, use 如果您要提取一个值,请使用

 var m = "[11/Sep/2016:21:58:55 +0000]".match(/\\[([^\\]]*)]/); console.log(m ? m[1] : "No match"); 

If there are more, use RegExp#exec with /\\[([^\\]]*)]/g and collect the matches: 如果还有更多, 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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