2

I have a regexp:

/(alpha)|(beta)|(gamma)/gi

Some text to match against:

Betamax. Digamma. Alphabet. Hebetation.

The matches are:

beta, gamma, alpha, beta

The values I am looking would be:

1,2,0,1

...can I ascertain the index of the group that matched in the regexp?

ekad
  • 14,436
  • 26
  • 44
  • 46
Matt Sephton
  • 3,711
  • 4
  • 35
  • 46

3 Answers3

5

To access the groups, you will need to use .exec() repeatedly:

var regex = /(alpha)|(beta)|(gamma)/gi,
    str = "Betamax. Digamma. Alphabet. Hebetation.";
for (var nums = [], match; match = regex.exec(str); )
    nums.push(match.lastIndexOf(match[0]));

If you want the indizes zero-based, you could use

    nums.push(match.slice(1).indexOf(match[0]));
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • This is my favourite so far, I love your use of manipulation of the results to get a zero-based result. – Matt Sephton Feb 16 '13 at 16:46
  • 1
    Yeah, it looks nice and allows us to use `indexOf` instead of backward search. Though, just appending `- 1` to the first one would be shorter and more performant :) – Bergi Feb 16 '13 at 16:48
1

Build your regex from an array of strings, and then lookup the matches with indexOf.

BnWasteland
  • 2,109
  • 1
  • 18
  • 14
1

If we consider the exact sample you provided, the below will work:

var r = /(alpha)|(beta)|(gamma)/gi;
var s = "Betamax. Digammas. Alphabet. Habetation.";

var matched_indexes = [];
var cur_match = null;

while (cur_match = r.exec(s))
{
    matched_indexes.push(cur_match[1] ? 0 : cur_match[2] ? 1 : 2 );
}

console.log(matched_indexes);

I leave it to you to make the content of the loop more dynamic / generic :p

Timothée Groleau
  • 1,940
  • 13
  • 16