AI智能
改变未来

Java/Kotlin 密码复杂规则校验

原文地址: 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位则返回falseif (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位则返回falseif (password.length < minLength || password.length > maxLength) return falsevar i = 0if (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)
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Java/Kotlin 密码复杂规则校验