2

为什么:

/(\[#([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

4

5 回答 5

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"
]
于 2012-09-12T15:08:39.170 回答
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"]
于 2012-09-12T15:14:58.697 回答
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"]
于 2012-09-12T15:11:55.347 回答
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++;
    }
于 2012-09-12T17:11:50.723 回答
0

在 ES2020 中添加了一个新功能matchAll女巫可以完成这项工作。

于 2020-10-30T11:43:03.530 回答