First of all, I know that using regex for email is not recommended but I gotta test this out.
I have this regex:
\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
In Java, I did this:
Pattern p = Pattern.compile("\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b");
Matcher m = p.matcher("foobar@gmail.com");
if (m.find())
System.out.println("Correct!");
However, the regex fails regardless of whether the email is wel-formed or not. A "find and replace" inside Eclipse works fine with the same regex.
Any idea?
Thanks,
FWIW, here is the Java code we use to validate email addresses. The Regexp's are very similar:
Works fairly reliably.
Regex :
^[\\w!#$%&’*+/=?
{|}~^-]+(?:\.[\w!#$%&’*+/=?{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$
Regex for Facebook-like validation:
Dto for Unit tests(with Lombok):
Valid/invalid emails below with Unit tests:
}
One another simple alternative to validate 99% of emails
Is maching set to CASE_INSENSITIVE?
Try the below code for email is format of
1st part
-jsmith
2nd part-@example.com