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. 2020/12/01 at 21:39

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: