Ash
Ash

Reputation: 1326

Regexp with global flag only matching first match

Why does:

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

return

["[#12345678]", "[#12345678]", "12345678"]

I want it to match all those numbers but it appears to be too greedy.

[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355] 12345678 87654321 56233001 36381069 23416459 56435355

Upvotes: 2

Views: 446

Answers (5)

Dvdgld
Dvdgld

Reputation: 2164

In ES2020 there is a new feature added matchAll witch does the job.

Upvotes: 0

Kash
Kash

Reputation: 9039

Try this:

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

Upvotes: 0

MicronXD
MicronXD

Reputation: 2220

regex.exec returns the groups in your regex (the things wrapped in parenthesis).

The function you're looking for is one you call on the string, match.

string.match(regex) returns all of the matches.

"[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355]".match(/(\[#([0-9]{8})\])/g)
// yields: ["[#12345678]", "[#87654321]", "[#56233001]", "[#36381069]", "[#23416459]", "[#56435355]"]

EDIT:

If you just want the numbers without the brackets and the #, just change the regex to /\d{8}/g

"[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355]".match(/[0-9]{8}/g)
// yields: ["12345678", "87654321", "56233001", "36381069", "23416459", "56435355"]

Upvotes: 1

Aidas Bendoraitis
Aidas Bendoraitis

Reputation: 4003

You can use replace method of a string to collect all the matches:

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

Upvotes: 1

gray state is coming
gray state is coming

Reputation: 2107

That's how .exec() works. To get multiple results, run it in a loop.

var re = /(\[#([0-9]{8})\])/g,
    str = "[#12345678] [#87654321] [#56233001] [#36381069] [#23416459] [#56435355]",
    match;

while (match = re.exec(str)) {
    console.log(match);
}

Also, the outer capture group seems extraneous. You should probably get rid of that.

/\[#([0-9]{8})\]/g,

Result:

[
    "[#12345678]",
    "12345678"
],
[
    "[#87654321]",
    "87654321"
],
[
    "[#56233001]",
    "56233001"
],
[
    "[#36381069]",
    "36381069"
],
[
    "[#23416459]",
    "23416459"
],
[
    "[#56435355]",
    "56435355"
]

Upvotes: 5

Related Questions