Created
October 1, 2020 08:48
-
-
Save akoppela/4620ed9f2fda1fc78ee5d49d2ce6c67b to your computer and use it in GitHub Desktop.
Basic regex parser
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
// n - text size, m = patter size | |
// Time: O(n+m), Space: O(m) | |
function isMatch(text, pattern) { | |
var tokens = tokenize(pattern); | |
var textPointer = 0; | |
var tokenPointer = 0; | |
while (tokenPointer < tokens.length) { | |
var token = tokens[tokenPointer]; | |
var char = findChar(text, textPointer); | |
if (token.isStar) { | |
if (token.value === '.') { | |
if (char === '') { | |
tokenPointer++; | |
} else { | |
token.value = char; | |
tokenPointer++; | |
textPointer++; | |
} | |
} else { | |
if (char === token.value) { | |
textPointer++; | |
} else { | |
tokenPointer++; | |
} | |
} | |
} else if (token.value === '.' || token.value === char) { | |
tokenPointer++; | |
textPointer++; | |
} else { | |
return false; | |
} | |
} | |
return findChar(text, textPointer) === ''; | |
} | |
function findChar(text, i) { | |
if (i >= text.length) { | |
return ''; | |
} | |
return text[i]; | |
} | |
function tokenize(pattern) { | |
var tokens = []; | |
for (var i = 0; i < pattern.length; i++) { | |
if (pattern[i] === '*') { | |
tokens[tokens.length - 1].isStar = true; | |
} else { | |
tokens.push({ value: pattern[i], isStar: false }); | |
} | |
} | |
return tokens; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment