Home >Java >javaTutorial >Why Doesn't My Java Regex Match Email Addresses?

Why Doesn't My Java Regex Match Email Addresses?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 14:49:12651browse

Why Doesn't My Java Regex Match Email Addresses?

Java Regex Email Validation

Question

A user has encountered difficulty using a regex for email validation in Java. Despite the regex matching in a "find and replace" operation within Eclipse, it fails to find email addresses using the Java Matcher class.

The user has provided the following regex:

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

In Java, the code they have written is:

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 to match regardless of whether the email is well-formed or not.

Answer

The provided regex is similar to the one used in the given Java code. However, there are a few key differences:

  • The provided regex uses character classes with braces, such as [A-Z0-9._%-] . In Java, these should be escaped as [A-Z0-9._%-] .
  • The provided regex uses dot as a literal character ., which should be escaped as \. using a double backslash in Java.
  • The provided regex uses a special character b to match the beginning of a word, which is not needed for email validation and can be removed.

The following Java code has been modified to address these issues:

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

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

With these modifications, the regex should now match email addresses in Java as expected.

The above is the detailed content of Why Doesn't My Java Regex Match Email Addresses?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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