Birjolaxew
Birjolaxew

Reputation: 817

Match repeating pattern using single group in regex

Using the JS regex object, is it possible to match a repeating pattern using a single, or few groups?

For instance, taking the following as input:

#222<abc#321cba#123>#111

Would it be possible to match both "#321" and "#123" (but not #222 or #111, as they're outside the /<.*?>/ group) using a regex similar to:

/<.*?(?:(#[0-9]+).*?)>/

(which currently only matches the first instance), when the number of matches in the input is unknown?

Upvotes: 0

Views: 244

Answers (1)

Hetzroni
Hetzroni

Reputation: 2174

You'd have to loop over the inner pattern. First use /<(.*?)>/ to extract it:

var outerRegex = /<(.*?)>/;
var match = outerRegex.exec(input);
var innerPattern = match[1];

Next, iterate over the result:

var innerRegex = /#\d+/g;
while (match = innerRegex.exec(innerPattern))
{
    var result = match[0];
    ...
}

Upvotes: 3

Related Questions