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

Why Doesn't My Java Regex Match Email Addresses?

Susan Sarandon
Release: 2024-12-06 14:49:12
Original
630 people have browsed it

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

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

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

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!

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