Skip to content

Instantly share code, notes, and snippets.

@furf
Created September 9, 2015 22:32
Show Gist options
  • Save furf/92bc0205c7be109c6294 to your computer and use it in GitHub Desktop.
Save furf/92bc0205c7be109c6294 to your computer and use it in GitHub Desktop.
Implement basic regex.
function regex(p, s) {
var pPointer = 0;
var pLength = p.length;
var pChar = '';
var sPointer = 0;
var sLength = s.length;
var sChar = '';
var wChar = '';
for (; sPointer < sLength; ++sPointer) {
sChar = s[sPointer];
pChar = p[pPointer];
if (pChar === '*' && sChar !== wChar) {
pPointer++;
if (pPointer === pLength) {
return true;
}
pChar = p[pPointer];
wChar = '';
}
if (sChar === pChar || pChar === '.' || pChar === '*') {
pPointer++;
wChar = sChar;
} else {
pPointer = 0;
}
if (pPointer === pLength) {
return true;
}
}
return false;
}
console.assert(regex('abb', 'abb'));
console.assert(regex('a*b', 'ab'));
console.assert(regex('a*b', 'aab'));
console.assert(regex('a*b', 'aaaab'));
console.assert(regex('a.b', 'aab'));
console.assert(regex('a.b', 'abb'));
console.assert(regex('a.b', 'acb'));
console.assert(!regex('cab', 'acb'));
console.assert(regex('ass', 'massage'));
console.assert(regex('a*', 'massage'), 'a*');
console.assert(regex('mas*age', 'massage'));
console.assert(regex('m..*age', 'massage'));
console.assert(regex('.*e', 'massage'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment