Get index of each capture in a JavaScript regex

后端 未结 7 859
一个人的身影
一个人的身影 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:15

    I created a little regexp Parser which is also able to parse nested groups like a charm. It's small but huge. No really. Like Donalds hands. I would be really happy if someone could test it, so it will be battle tested. It can be found at: https://github.com/valorize/MultiRegExp2

    Usage:

    let regex = /a(?: )bc(def(ghi)xyz)/g;
    let regex2 = new MultiRegExp2(regex);
    
    let matches = regex2.execForAllGroups('ababa bcdefghixyzXXXX'));
    
    Will output:
    [ { match: 'defghixyz', start: 8, end: 17 },
      { match: 'ghi', start: 11, end: 14 } ]
    

提交回复
热议问题