Javascript Regex string between first brackets including inside brackets


I have string like this

[test: test1: http://localhost?test=[1,2]]
[test: test2: http://localhost?test=[2,3]]

and I want to extract below from the text above

$1 = "test1"
$2 = "http://localhost?test=[1,2]"

$1 = "test2"
$2 = "http://localhost?test=[2,3]"

what I'm trying was

/\[test:(.*?):(.*?)\]/

but it returns like this. without "]"

$2 = "http://localhost?test=[2,3"

How can I change my regexp to get what I intented? thanks.

One fix to your regex would be to include the ] in the second group:

/\[test:(.*?):(.*?\])\]/
// add this ------^^

Another fix would be to have your existing \] at the end of the regex only match if it is at the end of the string:

/\[test:(.*?):(.*?)\]$/

As I guess, you get an URL as a second parameter. It will be really not pretty easy to make a correct regex which will include all possible URL values.

[test: test1: http://localhost?test=[1,2]]
[test: test1: http://localhost?test=[1,2]&somekey=somevalue]
[test: test1: http://localhost?test=[1,2]&answers=[1,2,3]]

You tried to find such regexp yourself. You came here, asked this question and spend so much of your expensive time trying to find a proper regular expression. And even if you now find such regular expression, did you really need it?

As a popular quote says:

Some people, when confronted with a problem, think "I know, I'll use regular expressions."
Now they have two problems.

It is up to your choice, I can only recommend but there is an easy, fast way which works with any data given in an input:

var str = "[test: test1: http://localhost?test=[1,2]]";
str = str.substring(1, str.length - 1);

var vals = str.split(': ');

console.log(vals[1]);
console.log(vals[2]);

No regular expressions, no headache. I don't want to say "don't use regex", I want to say "don't use it when it is not required" :)