Java regex email

Tu Hoang picture Tu Hoang · Nov 20, 2011 · Viewed 285k times · Source

First of all, I know that using regex for email is not recommended but I gotta test this out.

I have this regex:

\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

In Java, I did this:

Pattern p = Pattern.compile("\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b");
Matcher m = p.matcher("[email protected]");

if (m.find())
    System.out.println("Correct!");

However, the regex fails regardless of whether the email is wel-formed or not. A "find and replace" inside Eclipse works fine with the same regex.

Any idea?

Thanks,

Answer

Jason Buberel picture Jason Buberel · Nov 20, 2011

FWIW, here is the Java code we use to validate email addresses. The Regexp's are very similar:

public static final Pattern VALID_EMAIL_ADDRESS_REGEX = 
    Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);

public static boolean validate(String emailStr) {
        Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
        return matcher.find();
}

Works fairly reliably.