全局标志仅与第一个匹配项匹配的Regexp

Regexp with global flag only matching first match

本文关键字:Regexp 第一个 标志 全局      更新时间:2023-09-26

为什么:

/('[#([0-9]{8})'])/g.exec("[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355]")

返回

["[#1234678]"、"[#1345678]"answers"12345678"]

我希望它能匹配所有这些数字,但它似乎太贪婪了。

[#1234678][#87654321][#56230001][#336381069][#23416459][#556435355]12345678 87654321 56233001 36381069 23416459 56435355

.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"
]

您可以使用字符串的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"]

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"]

试试这个:

    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++;
    }

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