简体   繁体   中英

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

what Im doing wrong ?

You can use regex as : /[^\\[\\]]+/

 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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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