Wednesday, 24 September 2014

How to Validate Email Using RegularExpression


We can validate Email using regularExpression support given by JDK 

  EmailValidation.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidation{
    public static void main(String args[]){
        Pattern pattern;
        Matcher matcher;
        String email="suraj20p@gmail.com";
        String EMAIL_PATTERN = "^[_A-Za-z0-9]+(\\.[_A-Za-z0-9]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        //compile our pattern
        pattern = Pattern.compile(EMAIL_PATTERN);
        //pass our email to matcher,so that it can be checked whether pattern is matching or not
        matcher = pattern.matcher(email);
        //check whether string is matched or not
        boolean result= matcher.matches();
        if(result)
          System.out.println("Email Validated Successfully");
        else
           System.out.println("Invalid Email Address");
    
}

No comments:

Post a Comment