Java中正则校验的基本用法为:
String test = "希望校验的数据";
String regExp = "正则表达式";
boolean success = Pattern.compile(regExp).matcher(test).matches();
下面是一个基于正则的手机号、密码、邮箱格式检测工具类
public class Check {
/**
* 验证手机号格式
*
* @param phone 手机号
* @return 是否为手机号
*/
public static boolean isPhone(String phone) {
if (phone == null || phone.isEmpty()) {
return false;
}
String regExp = "^(?:(?:\\+|00)86)?1(?:(?:3[\\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\\d])|(?:9[1|8|9]))\\d{8}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(phone);
return m.matches();
}
/**
* 验证密码格式
*
* @param password 密码
* @return 密码是否正确
*/
public static boolean isPassword(String password) {
if (password == null || password.isEmpty()) {
return false;
}
String regExp = "^(?=.*[a-zA-Z])(?=.*\\d)(?=.*[.,;:'\"\\\\|~@#$%_&])[\\s\\S]{8,}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(password);
return m.matches();
}
/**
* 验证邮箱格式
* @param email 邮箱
* @return 邮箱是否正确
*/
public static boolean isEmail(String email) {
if (email == null || email.isEmpty()) {
return false;
}
String regExp = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\\\.][A-Za-z]{2,3}([\\\\.][A-Za-z]{2})?$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(email);
return m.matches();
}
}