Last active
August 19, 2022 02:25
-
-
Save stellasphere/d911b2ac86524ec25787e18242f8fd67 to your computer and use it in GitHub Desktop.
Better regex matching with better way to access groups
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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