Skip to content

Instantly share code, notes, and snippets.

@stellasphere
Last active August 19, 2022 02:25
Show Gist options
  • Save stellasphere/d911b2ac86524ec25787e18242f8fd67 to your computer and use it in GitHub Desktop.
Save stellasphere/d911b2ac86524ec25787e18242f8fd67 to your computer and use it in GitHub Desktop.
Better regex matching with better way to access groups
function match(string,regex) {
var matches = []
var m;
// Based on example code from regex101.com
while ((m = regex.exec(string)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
if(groupIndex == 0) matches.push({text:match,groups:[]})
matches[matches.length-1].groups.push(match)
});
}
return matches
}
function match(c,a){for(var b,d=[];null!==(b=a.exec(c));)b.index===a.lastIndex&&a.lastIndex++,b.forEach((a,b)=>{0==b&&d.push({text:a,groups:[]}),d[d.length-1].groups.push(a)});return d}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment