1

I am using a RegEx to match different possibilities.
What I need is a way to know which possilbility (group) is the match.

I've created a pretty simple snippet just to illustrate what I'd like to do:

var str = "aabbcc";
var re = /(aa)|(cc)/gi;
while ((match = re.exec(str)) != null) {
  console.log(match.index);
  // console.log(match.groupindex); <-- I need that
  // Doing things here for each match, so I can't really mess up all the RegEx
}

In case aa is matched it should return 1,
in case cc is matched it should return 2.

Is there any way to do that?

Thanks for any answer.
PS: As I am not a RegEx expert, any comment to enhance this piece of code would be welcomed as well.

EDIT:
Thanks for the “helpfull” link, but as I am using a function for each match, I can't just match everything like you have suggested by marking as duplicate.

Takit Isy
  • 9,688
  • 3
  • 23
  • 47
  • 1
    I love the dialog here, I asked and 2mins later my question is closed without giving me a proper solution. If there was a comment to suggest the link, I'd have say I can't do this. – Takit Isy Apr 19 '18 at 20:13
  • 1
    bring it up on meta – AnilRedshift Apr 19 '18 at 20:33
  • Unrelated to the dupe issue, but [it's not encouraged to "thanks" in Q&A](https://meta.stackexchange.com/questions/2950). – user202729 Apr 21 '18 at 04:14
  • About the dupe -- if I understood the question correctly the dupe is wrong, but it's hard to understand what the question is asking. You should explain more what you want (in case `aa` is matched return `1`, in case `cc` is matched return `2` -- correct?) – user202729 Apr 21 '18 at 04:30
  • [Same issue in c++](https://stackoverflow.com/questions/40801782/any-simple-way-to-get-which-alternative-got-matched-from-a-boostregex-match). – user202729 Apr 21 '18 at 04:36
  • @user202729us Yes, correct. I'm adding it to my question. – Takit Isy Apr 21 '18 at 04:59

0 Answers0