密码必须为长度8-20位且必须包含大,小写字母、数字、特殊符号 等三种字符
import java.util.regex.Pattern;
public class CheckPasswordUtil {
// 正则表达式:检查长度在8-20位之间
private static final String LENGTH_REGEX = "^.{8,20}$";
// 正则表达式:检查是否包含大写字母
private static final String UPPERCASE_REGEX = "[A-Z]";
// 正则表达式:检查是否包含小写字母
private static final String LOWERCASE_REGEX = "[a-z]";
// 正则表达式:检查是否包含数字
private static final String DIGIT_REGEX = "\\d";
// 正则表达式:检查是否包含特殊符号
private static final String SPECIAL_CHAR_REGEX = "[@#$%^&*()+=_\\-,.;'/|:<>?{}`~!\\[\\]\\\\]";
public static boolean validatePassword(String password) {
//检查长度
if (!password.matches(LENGTH_REGEX)) {
return false;
}
// 检查是否包含大写字母
boolean hasUppercase = Pattern.compile(UPPERCASE_REGEX).matcher(password).find();
// 检查是否包含小写字母
boolean hasLowercase = Pattern.compile(LOWERCASE_REGEX).matcher(password).find();
// 检查是否包含数字
boolean hasDigit = Pattern.compile(DIGIT_REGEX).matcher(password).find();
// 检查是否包含特殊符号
boolean hasSpecialChar = Pattern.compile(SPECIAL_CHAR_REGEX).matcher(password).find();
// 检查是否至少有三种不同类型的字符被找到
int count = (hasUppercase ? 1 : 0) +
(hasLowercase ? 1 : 0) +
(hasDigit ? 1 : 0) +
(hasSpecialChar ? 1 : 0);
if (count >= 3){
return true;
}
return false;
}
public static void main(String[] args) {
// 测试密码
String password = "12345abc?=";
String password2 = "12345abc";
boolean b = validatePassword(password);
boolean b2 = validatePassword(password2);
System.out.println(b);
System.out.println(b2);
}
}
效果展示