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

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 ?

5
  • 2
    There is no lookbehind in Javascript regex Commented Oct 4, 2016 at 10:02
  • How it should look then ? Coz it works fine in editor.. Commented Oct 4, 2016 at 10:04
  • 1
    Use str.match(/\[([^\]]*)\]/) and access the first index if you need one match only. Use /\[([^\]]*)\]/g with RegExp#exec and loop through all the matches to get all the values. Commented Oct 4, 2016 at 10:05
  • 1
    Well, editor is not using JS to evaluate. Try /\[([^\]]*)(?=\])/ and use captured group #1 Commented Oct 4, 2016 at 10:05
  • eh so tehre is no way to get text between chars ? :/ Ok I will drop first and last then ;) thanks Commented Oct 4, 2016 at 10:07

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.