Last active
January 11, 2024 11:35
-
-
Save jbreckmckye/10902046e1848a608a21f430affabfb8 to your computer and use it in GitHub Desktop.
Wildcard matching string function
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
"use strict"; | |
function matchWildcard(match, str) { | |
match = match.replace(/\*+/, '*'); | |
let sn = 0; | |
let m, s; | |
for (let mn = 0; mn < match.length; mn++, sn++) { | |
m = match[mn]; | |
s = str[sn]; | |
if (m === '*') { | |
// Bail out at end of match | |
if (mn == match.length - 1) { | |
return [sn <= str.length - 1, '* end']; // ending * matches 1..n remaining in str | |
} | |
// Ignore 1..Inf chars until next char = next match | |
let nextS = str[sn + 1]; | |
let nextM = match[mn + 1]; | |
while (nextS !== nextM && nextM !== '?' && sn < str.length) { | |
sn++; | |
nextS = str[sn + 1]; | |
} | |
continue; | |
} | |
if (m === '?') { | |
continue; // Ignore 1 character | |
} | |
if (m !== s) { | |
return [false, `mismatch ${m} ${s}`]; | |
} | |
} | |
if (sn !== str.length) { | |
return [false, `bad len ${sn} ${str.length}`]; // After completing the match, there are more chars | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment