How to check if email address is valid in Java

1 Answer

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

public class MyClass {
    public static boolean EmailValid(String email) { 
        String regex = "^[a-zA-Z0-9_+&*-]+(?:\\."+ 
                        "[a-zA-Z0-9_+&*-]+)*@" + 
                        "(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$"; 
                              
        if (email == null) 
            return false; 
            
        Pattern email_pat = Pattern.compile(regex); 
        
        return email_pat.matcher(email).matches(); 
    } 
    public static void main(String args[]) {
        String email = "a@email.com"; 
      
        System.out.println((EmailValid(email) == true) ? "yes" : "no");
      
        email = "a@email"; 
      
        System.out.println((EmailValid(email) == true) ? "yes" : "no");
      
        email = "a@email.co.uk"; 
      
        System.out.println((EmailValid(email) == true) ? "yes" : "no");
    }
}



/*
run:

yes
no
yes

*/

 



answered Sep 24, 2019 by avibootz
edited Sep 24, 2019 by avibootz

Related questions

2 answers 233 views
1 answer 190 views
1 answer 232 views
1 answer 204 views
1 answer 262 views
1 answer 80 views
...