直接上代码:
第一种:
String check = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z_]{8,20}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(password);
if(!matcher.matches()){
throw new MyParameterException(187, ApiConfirm._187);
}
不符合直接抛出异常,异常为自定义异常。
第二种:
/**
* 包含大小写字母及数字且在8-20位
* 是否包含
* @param str
* @return
*/
public static boolean isLetterDigit(String str) {
boolean isDigit = false;//定义一个boolean值,用来表示是否包含数字
boolean isLetter = false;//定义一个boolean值,用来表示是否包含字母
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) { //用char包装类中的判断数字的方法判断每一个字符
isDigit = true;
} else if (Character.isLetter(str.charAt(i))) { //用char包装类中的判断字母的方法判断每一个字符
isLetter = true;
}
}
String regex = "^[a-zA-Z0-9]{8,20}$";
boolean isRight = isDigit && isLetter && str.matches(regex);
return isRight;
}