Tuesday, November 29, 2016

Validate string with Regular Expression


Validating a string of characters is much easier with regular expressions than with a boolean expression where you would check if a character at a given position is within a range of legal characters.  You can us the Character class's isDigit, isLetter, isLetterOrDigit, or other methods in conjunction with the String charAt( ) method, but why would you do that when you have regular expression to match pattern much simpler. The Pattern class provides an easy to use way to match many complicated patterns of strings.

import java.util.regex.Pattern;
import java.util.regex.Matcher;

   /**
   Application to demonstrate of string validation based on regular expression
   @author Zoltan Szabo
   @version 1.0.0
   */
   public class MyClass{
   public static void main(String args[]){
  
    System.out.println(validate("234-L"));  //true
    System.out.println(validate("234-X"));  //false
    System.out.println(validate("234.L"));  //false
    System.out.println(validate("234-B"));  //true
    System.out.println(validate("234-b"));  //false
  
   }
   /**
   Validate string that is XXX-L format where X is a number 0-9 and L is a letter A-M and the length of the valid string is exactly 5 characters.
   @param s string to validate
   @return true or false based on the string validity
   */
   private static boolean validate(String s){
    boolean answer=true;
    if(s.length()!=5){
       answer=false;
    }
    else{
        Pattern p = Pattern.compile("[0-9]{3}-[A-M]");
        Matcher m = p.matcher(s);
        answer = m.matches();
    }
   return answer;
   }
  }

No comments:

Post a Comment