Get index of each capture in a JavaScript regex

后端 未结 7 818
一个人的身影
一个人的身影 2020-11-29 04:43

I want to match a regex like /(a).(b)(c.)d/ with \"aabccde\", and get the following information back:

\"a\" at index = 0
\"b\" at i         


        
7条回答
  •  北海茫月
    2020-11-29 05:20

    I wrote MultiRegExp for this a while ago. As long as you don't have nested capture groups, it should do the trick. It works by inserting capture groups between those in your RegExp and using all the intermediate groups to calculate the requested group positions.

    var exp = new MultiRegExp(/(a).(b)(c.)d/);
    exp.exec("aabccde");
    

    should return

    {0: {index:0, text:'a'}, 1: {index:2, text:'b'}, 2: {index:3, text:'cc'}}
    

    Live Version

提交回复
热议问题