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/
"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.
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.
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 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'.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With