Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regular expression iterator to extract groups

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.

like image 547
Pass Avatar asked Mar 02 '11 11:03

Pass


People also ask

What is capturing group in 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 first capturing group in regex?

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.

What is regex match group?

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.


1 Answers

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)

like image 92
Tim Pietzcker Avatar answered Sep 20 '22 03:09

Tim Pietzcker