I am using RegEx and exec to extract words but it is returning the full first match, not all the matches separately.
我使用RegEx和exec来提取单词,但它返回完整的第一个匹配,而不是单独的所有匹配。
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?
我错过了什么?
1 个解决方案
#1
2
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 ]
.
你也可以使用/\ [(。*?)\] / g where。*?将匹配除了]之外
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]);
}
#1
2
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 ]
.
你也可以使用/\ [(。*?)\] / g where。*?将匹配除了]之外
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]);
}