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.
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!