Thursday, August 24, 2017

regular expression match

Recently I coded in JS a lot. Its simplicity to make writing code extremely concise.

function regEx(p, w, i, j) {
if( i == p.length && j == w.length )
return true;
if ( j == w.length || i == p.length )
return false;
//if second char is *
if ( i+1<p.length && p.charAt(i+1) == '*' ){
//match pre char 0 time
if(regEx(p, w, i+2, j))
return true;
//match pre char 1+ times
for(let k = j; k<w.length && (p.charAt(i)==w.charAt(k) || p.charAt(i) == '.'); k++) {
if(regEx(p, w, i+2, k+1))
return true;
}
}
if(p.charAt(i) == w.charAt(j) || p.charAt(i) == '.') {
if(regEx(p, w, i+1, j+1))
return true;
}
return false;
}
view raw reg.js hosted with ❤ by GitHub