使用正则表达式验证邮箱,用户名,电话号码,固话号码,身份证,QQ号码等功能的Java实现 匹配返回类型为Boolean
下面是相关代码
static boolean flag = false;
public static boolean check(String str, String regex) {
try {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
flag = matcher.matches();
} catch (Exception e) {
flag = false;
}
return flag;
}
/**
* 验证邮箱
*
* @param email
* @return
*/
public static boolean checkEmail(String email) {
String regex = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
return check(email, regex);
}
/**
* @param cellphone
* @return
*/
public static boolean checkCellphone(String cellphone) {
String regex = "0?(13|14|15|18)[0-9]{9}";
return check(cellphone, regex);
}
/**
* 验证固话号码
*
* @param telephone
* @return
*/
public static boolean checkTelephone(String telephone) {
String regex = "[0-9-()()]{7,18}";
return check(telephone, regex);
}
/**
* 验证QQ号码
*
* @param QQ
* @return
*/
public static boolean checkQQ(String QQ) {
String regex = "[1-9]([0-9]{5,11})";
return check(QQ, regex);
}
/**
* 验证身份证号
* @param IdCard
* @return
*/
public static boolean checkIdCard(String IdCard){
String regex="\\d{17}[\\d|x]|\\d{15}";
return check(IdCard,regex);
}
/**
* 验证用户名
* @param userName
* @return
*/
public static boolean checkUserName(String userName){
String regex="[A-Za-z0-9_\\-\\u4e00-\\u9fa5]+";
return check(userName,regex);
}