我需要使用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 "));
}
}
Run Code Online (Sandbox Code Playgroud)
在java正则表达式中,你必须使用2个反斜杠来逃避.也就是说,\\
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 "));
}
}Run Code Online (Sandbox Code Playgroud)