uhop / node-re2

node.js bindings for RE2: fast, safe alternative to backtracking regular expression engines.
Other
489 stars 53 forks source link

Support for matchAll #128

Closed ThePendulum closed 2 years ago

ThePendulum commented 2 years ago

RE2 can be passed to String#match through the use of Symbols, which works well. String#matchAll, which returns the index and input for each match, will accept an RE2 instance, but will always return an empty array. It's not listed as being supported, but since there is a Symbol#matchAll, I was wondering if support for this and/or re2.match() could be attainable.

Thank you!

DavidSichau commented 2 years ago

We use the following ts code to achieve this:

if (typeof Symbol != 'undefined') {
  RE2.prototype[Symbol.matchAll] = function (str) {
    let cap: RegExpExecArray | null = null; // the single capture
    const all: Array<RegExpMatchArray> = []; // all the captures (return this)
    while ((cap = this.exec(str)) !== null) {
      all.push(cap);
    }
    return all.values();
  };
}