valoricDe / MultiRegExp2

Get all matches of a regexp with corresponding start and end positions
GNU General Public License v3.0
12 stars 5 forks source link

Use generator function #5

Closed valoricDe closed 7 years ago

eromoe commented 7 years ago

Hi, I mean something like python's re.finditer

re.finditer(pattern, string, flags=0) Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result unless they touch the beginning of another match.

https://docs.python.org/2/library/re.html

In javascript, would like

function* regexFindIter(re, text) {
  while ((m = re.exec(text)) !== null) {
    if (m.index === re.lastIndex) {
      re.lastIndex++;
    }

    m.forEach((match, groupIndex) => {
      yield match
    });
  }
}
valoricDe commented 7 years ago

Actually this implementation is only doing one exec. Therefore a generator function does not make much sense in this case. For getting only one Group you could call execForGroup(string, group). But thanks for the suggestion anyway.