"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does My Java Regex Email Validation Fail Despite Working in Eclipse's Find and Replace?

Why Does My Java Regex Email Validation Fail Despite Working in Eclipse's Find and Replace?

Published on 2024-12-22
Browse:152

Why Does My Java Regex Email Validation Fail Despite Working in Eclipse's Find and Replace?

Trouble with Java Regex Email Validation

In attempting to validate email addresses using a regular expression, a Java user has encountered a problem where the validation fails even for well-formed email addresses. Despite the fact that the regex matches email addresses when used in a "find and replace" function within Eclipse, it fails when used with Java's Pattern and Matcher classes.

The regex in question is:

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

The user has employed this code in Java:

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, regardless of the email address being valid or invalid, the regex validation fails.

A Potential Solution

A suggested solution is to utilize the following Java code, which employs a similar regex:

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.matches();
}

This code has been reported to validate email addresses reliably.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3