Monday, April 2, 2012

Regular Expressions in Java

A java standalone regular expression program which validates the given string for special characters

String custName="ABC 99 Conference Rm - # _')";

if this string should not allow $ ^ | these type of symbols



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

import org.apache.log4j.Logger;

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
String custName="ABC 99 Conference Rm - # _')";
Pattern namepattern = Pattern.compile("^$|^([-\\ \\# _\\(A-Z)(a-z)(0-9)'\\(\\)@&\\.\\:]){0,30}$");
boolean checkFlag = false;
if(custName.indexOf("+") >= 0){
System.out.println("+ is present");
}else if(custName.indexOf("%") >= 0){
System.out.println("% is present");
}else if(custName.indexOf("\"") >= 0){
System.out.println("\" is present");
}else if(custName.indexOf("/") >= 0){
System.out.println("\\ is present");
}else if(namepattern.matcher(custName).matches()){
            System.out.println("The given input matched the name pattern ");
            checkFlag = true;
        }
if(checkFlag){
System.out.println("First Name" +" is Valid");
}else{
System.out.println("Exceptions");
}
}

}


outcome
-----------

The given input matched the name pattern 
First Name is Valid