为什么:
/(\[#([0-9]{8})\])/g.exec("[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355]")
返回
[“[#12345678]”,“[#12345678]”,“12345678”]
我希望它能匹配所有这些数字,但它看起来太贪心了。
[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355] 12345678 87654321 56233001 36381069 23416459 56435355
答案 0 :(得分:5)
这就是.exec()
的工作方式。要获得多个结果,请循环运行。
var re = /(\[#([0-9]{8})\])/g,
str = "[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355]",
match;
while (match = re.exec(str)) {
console.log(match);
}
此外,外部捕获组似乎无关紧要。你可能应该摆脱它。
/\[#([0-9]{8})\]/g,
结果:
[
"[#12345678]",
"12345678"
],
[
"[#87654321]",
"87654321"
],
[
"[#56233001]",
"56233001"
],
[
"[#36381069]",
"36381069"
],
[
"[#23416459]",
"23416459"
],
[
"[#56435355]",
"56435355"
]
答案 1 :(得分:1)
regex.exec
返回正则表达式中的组(括号中包含的内容)。
您正在寻找的功能是您在字符串match
上调用的功能。
string.match(regex)
会返回所有匹配项。
"[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355]".match(/(\[#([0-9]{8})\])/g)
// yields: ["[#12345678]", "[#87654321]", "[#56233001]", "[#36381069]", "[#23416459]", "[#56435355]"]
编辑:
如果您只想要没有方括号和#的数字,只需将正则表达式更改为/\d{8}/g
"[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355]".match(/[0-9]{8}/g)
// yields: ["12345678", "87654321", "56233001", "36381069", "23416459", "56435355"]
答案 2 :(得分:1)
您可以使用字符串的replace
方法收集所有匹配项:
var s = "[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355]";
var re = /\[#([0-9]{8})\]/g;
var l = [];
s.replace(re, function($0, $1) {l.push($1)});
// l == ["12345678", "87654321", "56233001", "36381069", "23416459", "56435355"]
答案 3 :(得分:0)
试试这个:
var re = /\[#(\d{8})\]/g;
var sourcestring = "[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355]";
var results = [];
var i = 0;
var matches;
while (matches = re.exec(sourcestring)) {
results[i] = matches;
alert(results[i][1]);
i++;
}
答案 4 :(得分:0)
在ES2020中,添加了一个新功能matchAll由女巫完成。