Home > Java > javaTutorial > 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?

Barbara Streisand
Release: 2024-11-30 17:30:11
Original
641 people have browsed it

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
Copy after login

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!");
Copy after login

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();
}
Copy after login

This code has been reported to validate email addresses reliably.

The above is the detailed content of Why Does My Java Regex Email Validation Fail Despite Working in Eclipse's Find and Replace?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template