Menu

Sunday, July 10, 2011

Regular Expression - Validate email id

Here is a simple program to validate email id.


private static void validateEmailId () {

    String str1 = "test.email@domain.com";

    String expression = "^[\\w\\.-]+@[\\w\\.]+\\.[a-z]{2,3}$";
    Pattern pattern = Pattern.compile(expression);

    Matcher matcher = pattern.matcher(str1);

    boolean found = false;
    if (matcher.find()) {
        System.out.println (str1 + " - is a valid email id.");
        System.out.println (matcher.group(0));
        found = true;
    }
    if(!found){
        System.out.println(str1 + " - is not a valid email id.");
    }
}