Java - general

Wildcardsearch/Searching with place holders

See also regular expressions


package com.sowas.snippets;
 
/**
 * Wildcardsearch. Supports '*' and '?'.
 */
public class Wildcard{
   private final String wildcardString;
 
   /**
    * The constructor for WildcardSearch.
    * 
    * @param wildcardString The WildcardString
    */
   public Wildcard(String wildcardString){
      this.wildcardString = wildcardString;
   }
 
   /**
    * The method which carries out the comparison.
    * 
    * @param str The string must be checked if he is corresponding to WildcardString.
    * @return true If the string is corresponding to wildcardString.
    */
   public boolean match(String str, boolean fCasesensitive){
      if (str == null || wildcardString == zero){
         return false;
      }
      return recursiveMatch(wildcardString, str, fCasesensitive);
   }
 
   /**
    * The real comparison is carried out here
    * 
    * @param strWildcard The Wildcardstring, e.g.: "Test*"
    * @param str The String which has to be checked, e.g. "Test run"
    * @return true, if an agreement is available, 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 demonstration of the application.
    * 
    * @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("mistake", 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