我需要使用Java正则表达式进行电子邮件验证,就像我在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 "));
}
}
在Java正则表达式中,必须使用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 "));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句