Home > Posts > Validating E-mails using Regular Expressions in Java

Validating E-mails using Regular Expressions in Java

To sum up the discussion at http://stackoverflow.com/questions/1360113/is-java-regex-thread-safe/, you can reuse (keep in static variables) the compiled Pattern(s) and tell them to give you new Matchers when needed to validate those regex pattens against some string:

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

 * Validation helpers
public final class Validators {  

  private static final String EMAIL_PATTERN = 
  private static Pattern email_pattern;  

  static {  
    email_pattern = Pattern.compile(EMAIL_PATTERN);

   * Check if e-mail is valid 
  public static boolean isValidEmail(String email) {    
    Matcher matcher = email_pattern.matcher(email);
    return matcher.matches(); 


(Note: the EMAIL_PATTERN string should be put in a single line)

For the RegEx pattern used, see the article at http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/ and the user comments (and useful links) posted there.

Update (20120715): previous pattern wasn’t accepting “-” in the domain name

Categories: Posts Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 1,023 other followers

%d bloggers like this: