Christoph85LE
Christoph85LE

Reputation: 85

JS regexp: match repeated pattern

I wonder why these regexps aren't equivalent:

/(a)(a)(a)/.exec ("aaa").toString () => "aaa,a,a,a" , as expected
/(a){3}/.exec ("aaa").toString ()    => "aaa,a"      :(
/(a)*/.exec ("aaa").toString ()      => "aaa,a"      :(

How must the last two be reformulated so that they behave like the first? The important thing is that I want arbitrary multiples matched and remembered.

The following line

/([abc])*/.exec ("abc").toString () => "abc,c"

suggests that only one character is saved per parenthesis - the last match.

Upvotes: 4

Views: 2953

Answers (2)

Oriol
Oriol

Reputation: 288680

RegExBuddy describes it very well:

Note: you repeated the capturing group itself. The group will capture only the last iteration

Upvotes: 0

anubhava
anubhava

Reputation: 786291

You probably are looking for this:

var re = /([abc])/g,
    matches = [],
    input = "abc";
while (match = re.exec(input)) matches.push(match[1]);

console.log(matches);
//=> ["a", "b", "c"] 

Remember that any matching group will give you last matched pattern not all of them.

Upvotes: 5

Related Questions