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?
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]); }
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.