Java - general

Wildcardsearch/Search with free variables

See also Regular expressions


package com.sowas.snippets;
 
/**
 * Wildcardsearch. Supports '*' and '?'.
 */
public class Wildcard{
   private final String wildcardString;
 
   /**
    * The constructor for the WildcardSearch.
    * 
    * @param wildcardString The WildcardString
    */
   public Wildcard(String wildcardString){
      this.wildcardString = wildcardString;
   }
 
   /**
    * Method, which carries out the comparison.
    * 
    * @param str The String which shall be checked if it is in accordance with the WildcardString. 
    * @return true If the String is in accordance with the WildcardString.
    */
   public boolean match(String str, boolean fCasesensitive){
      if (str == zero || wildcardString == zero){
         return false;
      }
      return recursiveMatch(wildcardString, str, fCasesensitive);
   }
 
   /**
    * The real comparison is carried out here
    * 
    * @param strWildcard The Wildcardstring, z.B.: "test*"
    * @param str The String which is to be checked, z.B. "test run"
    * @return true, if an agreement exists, or else false
    */
   private boolean recursiveMatch(String strWildcard, String str, boolean fCasesensitive) {
      while (true){
         if (strWildcard.length() == 0)
            return str.length() == 0;
         char ch = strWildcard.charAt(0);
         switch (ch){
            case '?':
               if (str.length() == 0)
                  return false;
               break;
            case '*':
               strWildcard = strWildcard.substring(1);
               while (true){
                  if (recursiveMatch(strWildcard, str, fCasesensitive))
                     return true;
                  if (str.length() == 0)
                     return false;
                  str = str.substring(1);
               }
            default:
               if (str.length() == 0)
                  return false;
               if (fCasesensitive){
                  if (ch != str.charAt(0))
                     return false;
               }else
                  if (Character.toLowerCase(ch) != Character.toLowerCase(str.charAt(0)))
                     return false;
               break;
         }
         strWildcard = strWildcard.substring(1);
         str = str.substring(1);
      }
   }
 
   /**
    * A little demo of the use.
    * 
    * @param args
    */
   public static void main(String[] args){
      Wildcard wildcard1 = new Wildcard("Test*");
      System.out.println(wildcard1.match("Test run", true)); // true
      System.out.println(wildcard1.match("error", true)); // false
 
      Wildcard wildcard2 = new Wildcard("T?st");
      System.out.println(wildcard2.match("Test", true)); // true
      System.out.println(wildcard2.match("test", true)); // false
      System.out.println(wildcard2.match("test", false)); // true
   }
}

Eigene Werkzeuge
Werkzeuge

gratis Counter by GOWEB
seit 9.10.2007