原文地址: Java/Kotlin 密碼復雜度校驗 | Stars-One的雜貨小窩
每次有那個密碼復雜校驗,不會寫正則表達式,每次都去搜,但有時候校驗的條件又是奇奇怪怪的,百度都搜不到
找到了個代碼判斷的方法,每次匹配計算匹配的次數,最后在用次數來作為判斷是否滿足的條件即可
Java
package site.starsone.demo;
public class CheckPwdUtils {
//數字
public static final String REG_NUMBER = ".*\\d+.*";
//小寫字母
public static final String REG_UPPERCASE = ".*[A-Z]+.*";
//大寫字母
public static final String REG_LOWERCASE = ".*[a-z]+.*";
//特殊符號
public static final String REG_SYMBOL = ".*[~!@#$%^&*()_+|<>,.?/:;'\\[\\]{}\"]+.*";
/**
* 長度至少minLength位,且最大長度不超過maxlength,須包含大小寫字母,數字,特殊字符matchCount種以上組合
* @param password 輸入的密碼
* @param minLength 最小長度
* @param maxLength 最大長度
* @param matchCount 次數
* @return 是否通過驗證
*/
public static boolean checkPwd(String password,int minLength,int maxLength,int matchCount){
//密碼為空或者長度小於8位則返回false
if (password == null || password.length() <minLength || password.length()>maxLength ) return false;
int i = 0;
if (password.matches(REG_NUMBER)) i++;
if (password.matches(REG_LOWERCASE))i++;
if (password.matches(REG_UPPERCASE)) i++;
if (password.matches(REG_SYMBOL)) i++;
return i >= matchCount;
}
}
使用
//長度至少為8位,最大為20位,包含數字 小寫字母 大寫字母 特殊符號任意兩種及以上
CheckPwdUtils.checkPwd("123456", 8, 20, 2)
Kotlin
object CheckPwdUtils {
//數字
const val REG_NUMBER = ".*\\d+.*"
//小寫字母
const val REG_UPPERCASE = ".*[A-Z]+.*"
//大寫字母
const val REG_LOWERCASE = ".*[a-z]+.*"
//特殊符號
const val REG_SYMBOL = ".*[~!@#$%^&*()_+|<>,.?/:;'\\[\\]{}\"]+.*"
/**
* 長度至少minLength位,且最大長度不超過maxlength,須包含大小寫字母,數字,特殊字符matchCount種以上組合
* @param password 輸入的密碼
* @param minLength 最小長度
* @param maxLength 最大長度
* @param matchCount 次數
* @return 是否通過驗證
*/
fun checkPwd(password: String, minLength: Int, maxLength: Int, matchCount: Int): Boolean {
//密碼為空或者長度小於8位則返回false
if (password.length < minLength || password.length > maxLength) return false
var i = 0
if (password.matches(Regex(REG_NUMBER))) i++
if (password.matches(Regex(REG_LOWERCASE))) i++
if (password.matches(Regex(REG_UPPERCASE))) i++
if (password.matches(Regex(REG_SYMBOL))) i++
return i >= matchCount
}
}
使用
val pwd = "123456"
//長度至少為8位,最大為20位,包含數字 小寫字母 大寫字母 特殊符號任意兩種及以上
CheckPwdUtils.checkPwd(pwd, 8, 20, 2)