之前項目要驗證email的有效性,由於偷懶在網上抄了一個正則,如下
public static boolean isEmail(String string) {
if (string == null)
return false;
String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";//這個是沒有用的
Pattern p;
Matcher m;
p = Pattern.compile(rule);
m = p.matcher(string);
if (m.matches())
return true;
else
return false;
}
本以爲網上都是這樣寫的,應該沒事,直到上線才發現問題。
要改成如下這樣才行,上面的是無效的。
public static boolean isEmail(String string) {
if (string == null)
return false;
String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";//這個是沒有用的
String rule = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
Pattern p;
Matcher m;
p = Pattern.compile(rule);
m = p.matcher(string);
if (m.matches())
return true;
else
return false;
}