Skip to content

Instantly share code, notes, and snippets.

@legendtang
Created July 30, 2015 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save legendtang/17bc0d91135919e2b19d to your computer and use it in GitHub Desktop.
Save legendtang/17bc0d91135919e2b19d to your computer and use it in GitHub Desktop.
Reg Expression Mod - '*' matches zero or more the entire preceding element (one byte or more) while '.' does the normal Reg Expressions did.
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function(s, p) {
// console.log({'s':s,'p':p});
var pend = p.length - 1;
var send = s.length - 1;
if( s === '' && (p === '' || p[pend] === '*') || s.length == 1 && p == '.') {
return true
}
if( s.length && p.length === 0) {
// console.log(false);
return false
}
if( s.length == 1 && p.length == 2 && p[pend] == '*') {
if ( s == p[0] ) return true;
else return false
}
else if( p[pend] == s[send] || ( p[pend] == '.' && s[send - 1] !== undefined ) ){
return isMatch(s.slice(0, -1), p.slice(0, -1))
}
else if( p[pend] == '*' && p[pend - 1] !== undefined ) {
if ( p[pend - 1] == '.' ) {
return isMatch( s.slice(0, p.slice(0, -2).length ), p.slice(0, -2))
}
var count = 1;
while ( count <= p.length ){
// console.log({'s':s,'p':p});
// console.log({"p.slice( -count - 1, -1 )":p.slice( -count - 1, -1 ), "s.slice( -count )": s.slice( -count )})
// console.log({'p.slice(0, -count - 1)' : p.slice(0, -count - 1)})
if( p[pend - 1] == '.' ) {
count = 2;
break;
} else if( p.slice( -count - 1, -1 ) == s.slice( -count ) ) {
// console.log({'p.slice( -count - 2, -1 )': p.slice( -count - 2, -1 )});
// console.log({'count':count});
if( s.length == count ) return true;
else if( -1 == p.slice( -count - 2, -1 ).indexOf('*') && s[send - count] == p[pend - count - 1] && s[send - count] !== '') {
// console.log(p.slice( -count - 2, -1 ).indexOf('*'));
count++;
// console.log(count);
}
else {
// console.log('do');
// console.log({'s':s,'p':p});
// console.log({"p.slice( -count - 1, -1 )":p.slice( -count - 1, -1 ), "s.slice(-count * 2, -count )":s.slice(-count * 2, -count )})
if( p.slice( -count - 1, -1 ) == s.slice(-count * 2, -count ) )
return isMatch( s.slice(0, -count), p )
else return isMatch( s.slice(0, -count), p.slice( 0, -count - 1 ) )
// else return isMatch( s.slice(0, -count), p );
}
} else {
// console.log('5');
// console.log({'s':s,'p':p});
if( count > 1 ) {
// console.log(count);
// console.log(s.slice(0, -count ));
return isMatch( s.slice(0, count == s.length ? s.length : -count ), p );
} else return isMatch( s, p.slice(0, - count - 1) );
}
}
// console.log({'s.slice(0, -count + 1)': s.slice(0, -count + 1), 'p.slice(0, -count)': p.slice(0, -count)})
return isMatch(s.slice(0, -count + 1), p.slice(0, -count ))
}
else return false
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment