When my RegExp has several capture groups, I want to know which group made the capture (or at least the first / last group, if there were several). If you are familiar with Python, this is basically the equivalent of re.MatchObject.lastgroup . Some code to make it clearer:
var re_captures = new RegExp("(\\d+)|(for)|(\\w+)", "g"); var str = " for me 20 boxes please"; var result; while ((result = re_captures.exec(str)) !== null) { console.log(result[0], 'at', result.index, result.slice(1)); }
He prints:
for at 1 [ undefined, 'for', undefined ] me at 5 [ undefined, undefined, 'me' ] 20 at 8 [ '20', undefined, undefined ] boxes at 11 [ undefined, undefined, 'boxes' ] please at 17 [ undefined, undefined, 'please' ]
The result array shows which groups made the capture, but I see no way to quickly find out for each given match which group was matched without iterating through the array. This is useful in cases where large regular expressions are created programmatically and the iteration is inefficient.
Am I missing something obvious or not possible?
source share