RegEx to extract all matches from string using RegExp.exec

前端 未结 17 1597
-上瘾入骨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:12

    Iterables are nicer:

    const matches = (text, pattern) => ({
      [Symbol.iterator]: function * () {
        const clone = new RegExp(pattern.source, pattern.flags);
        let match = null;
        do {
          match = clone.exec(text);
          if (match) {
            yield match;
          }
        } while (match);
      }
    });
    

    Usage in a loop:

    for (const match of matches('abcdefabcdef', /ab/g)) {
      console.log(match);
    }
    

    Or if you want an array:

    [ ...matches('abcdefabcdef', /ab/g) ]
    

提交回复
热议问题