How to find indices of groups in JavaScript regular expressions match?

后端 未结 6 607
温柔的废话
温柔的废话 2020-12-09 09:33

When I write a regular expression like:

var m = /(s+).*?(l)[^l]*?(o+)/.exec(\"this is hello to you\");
console.log(m);

I get a match object

6条回答
  •  抹茶落季
    2020-12-09 09:53

    For global regex you want to match only fragments and iterate so first solution won't work. This is a 30 min solution based on indexOf and sums that work for this case:

    https://codepen.io/cancerberoSgx/pen/qYwjjz?editors=0012#code-area

    !function () {
      const regex = /\/\*\*\*@\s*([^@]+)\s*(@\*\*\*\/)/gim
      const exampleThatMatch = `
        /***@
        debug.print('hello editor, simpleNode kind is ' +
        arg.simpleNode.getKindName())
        @***/
    
        const a = 1 //user
    
        /***@
        debug.print(arg.simpleNode.getParent().getKindName())
        @***/
        `
      const text = exampleThatMatch 
      function exec(r, s) {
        function indexOfGroup(match, n) {
          var ix = match.index;
          for (var i = 1; i < n; i++)
            ix += match[i].length;
          return ix;
        }
        let result
        let lastMatchIndex = 0
        const matches = []
        while ((result = regex.exec(text))) {
          const match = []
          lastMatchIndex = text.indexOf(result[0], lastMatchIndex)
          let relIndex = 0 
          for (let i = 1; i < result.length; i++) {
            relIndex = text.indexOf(result[i], relIndex)
            match.push({ value: result[i], start: relIndex, end: relIndex + result[i].length })
          }
          matches.push(match)
        }
        return matches
      }
      const groupsWithIndex = exec(regex, text)
      console.log({RESULT: groupsWithIndex })
      // now test - let's remove everything else but matched groups 
      let frag = '' , sep = '\n#######\n'
      groupsWithIndex.forEach(match => match.forEach(group => {
        frag += text.substring(group.start, group.end) + sep
      }))
      console.log('The following are only the matched groups usign the result and text.substring just to verify it works OK:', '\n'+sep)
      console.log(frag)
    }()
    

    And just in case here is the typescript:

    https://codepen.io/cancerberoSgx/pen/yjrXxx?editors=0012

    | Enjoy

提交回复
热议问题