电子邮件验证正则表达式 JAVA
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42266148/
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 validation Regex JAVA
提问by Techie
I have a requirement to have email validation using java regex same as I already have on JSP. When I am copying regex from JSP to JAVA, I am getting an error.However, in JSP it is working fine.
我需要使用 java regex 进行电子邮件验证,就像我已经在 JSP 上一样。当我将正则表达式从 JSP 复制到 JAVA 时,出现错误。但是,在 JSP 中它工作正常。
if (null != email) {
String regex = "^([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{1,6}))?$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
if (!matcher.matches()) {
addFormException(new DropletException("Email not valid "));
}
}
回答by Sagar V
In java regex, you have to use 2 backslashes to escape. Ie, \\
在 java regex 中,您必须使用 2 个反斜杠来转义。IE,\\
if (null != email) {
String regex = "^([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{1,6}))?$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
if (!matcher.matches()) {
addFormException(new DropletException("Email not valid "));
}
}
回答by user2844511
I am assuming you are having issue with your regex.Please use below regex expression and try run your code. Your above code has only one slash.
我假设您的正则表达式有问题。请使用下面的正则表达式并尝试运行您的代码。你上面的代码只有一个斜杠。
String regex = "^([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{1,6}))?$";