Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: How to match one capture group multiple times in the same string?

The Situation

I have a string that I want to match the same capture group multiple times. I need to be able to get at both matches.

Example Code

var curly = new RegExp("{([a-z0-9]+)}", "gi");
var stringTest = "This is a {test} of my {pattern}";

var matched = curly.exec(stringTest);
console.log(matched);

The Problem

Right now, it only shows the first match, not the second.

JSFiddle Link

http://jsfiddle.net/npp8jg39/

like image 948
Jake Avatar asked Oct 15 '14 21:10

Jake


People also ask

How do you repeat a group in regex?

"Capturing a repeated group captures all iterations." In your regex101 try to replace your regex with (\w+),? and it will give you the same result. The key here is the g flag which repeats your pattern to match into multiple groups.

Does special group and group 0 is included while capturing groups using groupCount?

The group() method is one of several capturing group-oriented Matcher methods: int groupCount() returns the number of capturing groups in a matcher's pattern. This count doesn't include the special capturing group number 0, which denotes the entire pattern. String group() returns the previous match's characters.

What is a capture group regex Javascript?

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.

What is regex grouping?

What is Group in Regex? A group is a part of a regex pattern enclosed in parentheses () metacharacter. We create a group by placing the regex pattern inside the set of parentheses ( and ) . For example, the regular expression (cat) creates a single group containing the letters 'c', 'a', and 't'.


1 Answers

Try this:

    var curly = /{([a-z0-9]+)}/gi,
        stringTest = "This is a {test} of my {pattern}",
        matched;
    while(matched = curly.exec(stringTest))
        console.log(matched);
like image 55
Oriol Avatar answered Oct 19 '22 23:10

Oriol