Gene9y Gene9y - 22 days ago 6
Javascript Question

RegEx to extract words in brackets not working

I am using RegEx and exec to extract words but it is returning the full first match, not all the matches separately.

The string is

'one two [three four] five [six] seven [nine ten]'
. The result should be
'three four'
,
'six'
,
'nine ten'
, instead of
'[three four] five [six] seven [nine ten]'
.

var text = "one two [three four] five [six] seven [nine ten]"
var brackets = /\[([^]+)\]/g;
var match;
while (match = brackets.exec(text)) {
console.log(match);
}


What am I missing?

Answer

The problem is with the capturing group ([^]+).

[^]+ matches any character, including newline as there is nothing specified in the negated character class.

Use the below regex

/\[([^[\]]+)\]/g

[^[\]]+: will match one or more characters except square brackets [ and ].

var text = "one two [three four] five [six] seven [nine ten]"
var brackets = /\[([^[\]]+)\]/g;
var match;
while (match = brackets.exec(text)) {
    console.log(match[1]);
}


You can also use /\[(.*?)\]/g where .*? will match anything except ].

var text = "one two [three four] five [six] seven [nine ten]"
var brackets = /\[(.*?)\]/g;
var match;
while (match = brackets.exec(text)) {
    console.log(match[1]);
}