高安全性密码的正则表达式验证

在许多情况下,要求用户的必须符合规则:包含数字,小写英文字母,大写英文字母,特殊字符~!@#$%^&之一,且长度必须>=6

有许多方法,其中一个是正则表达式.

在java中使用正则表达式,并不是很方便,最后还是使用:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

具体代码如下(此处没有检验长度,只是检验是否包含特定字符):

/**
     * @author lzf
     * @created on 2019年10月24日 下午2:48:38
     * @功能   判断密码是否都包含了 数字,小写英文字母,大写英文字母,特别符号(~!@#$%^&*_)
     * @param passwd 明文密码字符串
     * @return  如果都包含,则返回true,否则返回false..
     */
    private boolean isPassWordValid(String passwd){
        String regExpS="(?<one>[0-9])|(?<two>[a-z])|(?<four>[A-Z])|(?<three>[~!@#$%^&*_])";
        Pattern r = Pattern.compile(regExpS);
        Matcher isMatch = r.matcher(passwd);
        boolean isFindNumberOk=false;
        boolean isFindSmallAlphabetOk=false;
        boolean isFindBigAlphabetOk=false;
        boolean isFindSpecialSymblOk=false;
        while (isMatch.find()){
            String one=isMatch.group("one");
            if (one!=null && isFindNumberOk==false){
                isFindNumberOk=true;
            }
            String two=isMatch.group("two");
            if (two!=null && isFindSmallAlphabetOk==false){
                isFindSmallAlphabetOk=true;
            }
            String three=isMatch.group("three");
            if (three!=null && isFindSpecialSymblOk==false){
                isFindSpecialSymblOk=true;
            }
            String four=isMatch.group("four");
            if (four!=null && isFindBigAlphabetOk==false){
                isFindBigAlphabetOk=true;
            }
            //System.out.println(one+"--"+two+"----"+three+"----"+four);
        }
        
        if (  isFindNumberOk && isFindSmallAlphabetOk && isFindBigAlphabetOk && isFindSpecialSymblOk){
            return true;                    
            //System.out.println("在字符串["+srcStr+"]中发现了数字、小写字母、大写字母和特定符号");
        }
        else{
            return false;
        }
    }

上面的代码,可以满足结果,但不是很高效,甚至特定情况下,不如逐个分析字符串来得高效。不过用于验证密码输入是否满足规则的业务通常对性能要求不高,所以也可以将就!

猜你喜欢

转载自www.cnblogs.com/lzfhope/p/11740594.html
今日推荐