Guest User

Untitled

a guest
Jun 18th, 2013
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.44 KB | None | 0 0
  1. public boolean regexMatch(char[] src, char[] regex){
  2.     return regexMatch(src, regex, 0, 0);
  3. }
  4.  
  5. private boolean regexMatch(char[] src, char[] regex, int currIndex, int regexIndex){
  6.     if(regexIndex == regex.length){
  7.         return (currIndex == src.length);
  8.     }
  9.    
  10.     // At no point in time, [star] cannot be our starting char in regex
  11.     if(regex[regexIndex] == '*'){
  12.         throw new RuntimeException("Invalid Regex ..");
  13.     }
  14.    
  15.     if(currIndex == src.length){
  16.         // if the current char in regex is not followed by a [star], then there is no match
  17.         while(regex.length > regexIndex+1 && regex[regexIndex+1] == '*'){
  18.             regexIndex += 2;
  19.         }
  20.         return (regex.length == regexIndex);
  21.     }
  22.    
  23.     // If the char is a dot
  24.     if(regex[regexIndex] == '.'){
  25.         // See if the subsequent char is a [star]
  26.         if(regexIndex+1 < regex.length && regex[regexIndex+1] == &#039;*&#039;){
  27.                 // Three cases are possible
  28.                 // a. consider there is a match and move the currIndex
  29.                 // b. consider there is a match and move both currIndex and regexIndex
  30.                 // c. consider there is no match and move the regexIndex
  31.                 return regexMatch(src, regex, currIndex+1, regexIndex) || regexMatch(src, regex, currIndex+1, regexIndex+2) || regexMatch(src, regex, currIndex, regexIndex+2);
  32.         } else {
  33.             return regexMatch(src, regex, currIndex+1, regexIndex+1);
  34.         }
  35.     } else {
  36.         // See if the subsequent char is a [star]
  37.         if(regexIndex+1 < regex.length && regex[regexIndex+1] == &#039;*&#039;){
  38.                 if(src[currIndex] == regex[regexIndex]){
  39.                     // Three cases are possible
  40.                     // a. consider there is a match and move the currIndex
  41.                     // b. consider there is a match and move both currIndex and regexIndex
  42.                     // c. consider there is no match and move the regexIndex
  43.                     return regexMatch(src, regex, currIndex+1, regexIndex) || regexMatch(src, regex, currIndex+1, regexIndex+2);
  44.                 }
  45.                 // NOTE: this represents the (c) case, both when the char does match and when it does not
  46.                 return regexMatch(src, regex, currIndex, regexIndex+2);
  47.         } else {
  48.             return src[currIndex] == regex[regexIndex] && regexMatch(src, regex, currIndex+1, regexIndex+1);
  49.         }
  50.     }    
  51. }
Advertisement
Add Comment
Please, Sign In to add comment