Java 当域名带有连字符时电子邮件地址验证失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16295329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Email address validation fails when domain name has a hyphen
提问by ErrorNotFoundException
I have an email address validation regex Which I use in the code like this:
我有一个电子邮件地址验证正则表达式,我在代码中使用它,如下所示:
public class Test {
public static void main(String[] args) {
try {
String lineIwant = "[email protected]";
String emailreg = "^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$";
Boolean b = lineIwant.matches(emailreg);
if (b == false) {
System.out.println("Address is Invalid");
}else if(b == true){
System.out.println("Address is Valid");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
On this specific email address in the example, the Boolean returns false while this is a valid customer email address.
在示例中的此特定电子邮件地址上,布尔值返回 false,而这是有效的客户电子邮件地址。
I am suspecting it is because of the hyphen between ramco
and group
because when I remove it the Boolean returns true.
我怀疑这是因为之间的连字符ramco
,group
因为当我删除它时,布尔值返回 true。
How can I change my regex to accommodate such an email address?
如何更改我的正则表达式以适应这样的电子邮件地址?
采纳答案by Tim Pietzcker
Your regex is not allowing a -
after the @
sign, so
您的正则表达式不允许-
在@
符号后使用a ,所以
String emailreg = "^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,})$";
would "fix" this specific problem. But Email addresses are much more complicated than that. Validating them using a regex is not a good idea. Check out @DuncanJones' comment.
将“修复”这个特定问题。但电子邮件地址比这复杂得多。使用正则表达式验证它们不是一个好主意。查看@DuncanJones 的评论。
回答by gmustudent
Add \\-
to that section of the regex string after the @
.
添加\\-
到@
.
The \\
is an escape telling Java that you do not want to use the dash as it's normally used to show the difference between two values. So like this...
这\\
是一个转义,告诉 Java 您不想使用破折号,因为它通常用于显示两个值之间的差异。所以像这样...
^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9\-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$
Update
更新
Tim acknowledged in the comments that the escape is not necessary!
蒂姆在评论中承认没有必要逃跑!
And a quick tip of my own is you might want to use \w
in replace of [A-Za-z0-9_]
so you don't have to keep writing that over and over. And finally get familiar with this site. Once you start using regex it's a great help.
我自己的一个快速提示是,您可能想要使用\w
代替,[A-Za-z0-9_]
这样您就不必一遍又一遍地写。终于熟悉了这个网站。一旦您开始使用正则表达式,它就会有很大帮助。
回答by MarekM
回答by Duncan Jones
I would recommend you don't try to solve this problem yourself. Instead, rely on a well-tested solution such as EmailValidator
from commons-validator.
我建议您不要尝试自己解决这个问题。相反,依靠经过良好测试的解决方案,例如EmailValidator
来自commons-validator。
For example:
例如:
EmailValidator.getInstance().isValid(emailAddressString);