let's say we have the following text: "1 a,2 b,3 c,4 d" and the following expression: /\d (\w)/g
what we want to do is to extract a, b, c, d as denoted by the regular expression.
unfortunately "1 a,2 b,3 c,4 d".match(/\d (\w)/g) will produce an array: 1 a,2 b,3 c,4 d and RegExp.$1 will contain only the groups from the last match, i.e. RegExp.$1 == 'd'.
how can I iterate over this regex so that I can extract the groups as well... I am looking for a solution that is also memory efficient, i.e. some sort of iterator object
EDIT: It needs to be generic. I am only providing a simple example here. One solution is to loop over the array and reapply the regex for each item without the global flag but I find this solution a bit stupid although it seems to be like the only way to do it.
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.
First group matches abc. Escaped parentheses group the regex between them. They capture the text matched by the regex inside them into a numbered group that can be reused with a numbered backreference. They allow you to apply regex operators to the entire grouped regex.
Regular expressions allow us to not just match text but also to extract information for further processing. This is done by defining groups of characters and capturing them using the special parentheses ( and ) metacharacters. Any subpattern inside a pair of parentheses will be captured as a group.
var myregexp = /\d (\w)/g;
var match = myregexp.exec(subject);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
match = myregexp.exec(subject);
}
(shamelessly taken from RegexBuddy)
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