RegEx to extract all matches from string using RegExp.exec

前端 未结 17 1503
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:49

I\'m trying to parse the following kind of string:

[key:\"val\" key2:\"val2\"]

where there are arbitrary key:\"val\" pairs inside. I want t

17条回答
  •  梦如初夏
    2020-11-22 03:23

    str.match(/regex/g)
    

    returns all matches as an array.

    If, for some mysterious reason, you need the additional information comes with exec, as an alternative to previous answers, you could do it with a recursive function instead of a loop as follows (which also looks cooler).

    function findMatches(regex, str, matches = []) {
       const res = regex.exec(str)
       res && matches.push(res) && findMatches(regex, str, matches)
       return matches
    }
    
    // Usage
    const matches = findMatches(/regex/g, str)
    

    as stated in the comments before, it's important to have g at the end of regex definition to move the pointer forward in each execution.

提交回复
热议问题