Skip to content

Instantly share code, notes, and snippets.

@RReverser
Last active March 4, 2016 21:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RReverser/a458efc70909e9ef907a to your computer and use it in GitHub Desktop.
Save RReverser/a458efc70909e9ef907a to your computer and use it in GitHub Desktop.
RegExp.prototype.matches = function* (str) {
let moreThanOnce = this.global || this.sticky;
let myLastIndex = 0;
do {
// preserve lastIndex of another .exec() calls on same regexp
let savedLastIndex = this.lastIndex;
// use own state for lastIndex to match our str
this.lastIndex = myLastIndex;
let match = this.exec(str);
// save new state & restore lastIndex for other .exec() calls
myLastIndex = this.lastIndex;
this.lastIndex = savedLastIndex;
if (!match) break;
yield match;
} while (moreThanOnce);
};
var r = /[a-z]/g;
// 1) Just iterating
for (let match of r.matches('abc')) {
console.log(match);
}
/*
["a"]
["b"]
["c"]
*/
// 2) Concurrent iterators - not easy with regular re.exec()
var iter1 = r.matches('abc');
var iter2 = r.matches('def');
for (let i = 0; i < 3; i++) {
console.log('iter1:', iter1.next().value);
console.log('iter2:', iter2.next().value);
}
/*
iter1: ["a"]
iter2: ["d"]
iter1: ["b"]
iter2: ["e"]
iter1: ["c"]
iter2: ["f"]
*/
// 3) All matched groups - requires manual collection with .exec
var matches = Array.from(/(\w+)=(\d+)/g.matches('x=1,y=2'));
/*
[
[ 'x=1', 'x', '1' ],
[ 'y=2', 'y', '2' ]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment