Java 正则表达式电子邮件 [英] Java regex email
本文介绍了Java 正则表达式电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
首先,我知道不建议在电子邮件中使用正则表达式,但我必须对此进行测试.
First of all, I know that using regex for email is not recommended but I gotta test this out.
我有这个正则表达式:
[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z]{2,4}
在 Java 中,我是这样做的:
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!");
但是,无论电子邮件格式是否正确,正则表达式都会失败.Eclipse 中的查找和替换"可以使用相同的正则表达式正常工作.
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.
有什么想法吗?
谢谢,
推荐答案
FWIW,这里是我们用来验证电子邮件地址的 Java 代码.正则表达式非常相似:
FWIW, here is the Java code we use to validate email addresses. The Regexp's are very similar:
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.find();
}
工作相当可靠.
这篇关于Java 正则表达式电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文