My post about Java regular expression gets a lot of hits daily. Someone commented that the regular expression I included in that post does not block certain invalid email addresses. So I updated the Java regular expression to validate email address. I am pretty sure that the following Java regular expression will validate any email address.

"^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";


Here is an example Java program to test this regular expression for email address validation.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidateEmailAddress{
  
 public boolean isValidEmailAddress(String emailAddress){
   String  expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
   CharSequence inputStr = emailAddress; 
   Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
   Matcher matcher = pattern.matcher(inputStr);
   return matcher.matches();
  
 }
 public static void main(String args[]){
    ValidateEmailAddress vea = new ValidateEmailAddress();
    String emailAddress = "ab.cd@xyz.com";
    if(vea.isValidEmailAddress(emailAddress)){
     System.out.println(emailAddress + " is a valid email address.");
   }else{
     System.out.println(emailAddress + " is an invalid email address.");
   }
 }
}



Give this regular expression a try. I am confident that no invalid email can get through this regular expression.

Enjoy.

If you enjoyed this post, make sure you subscribe to my RSS feed!