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.
The provided regex is similar to the one used in the given Java code. However, there are a few key differences:
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!