liukangdong
2024-10-21 4e45a8252d7bccd23a1a57aa541a2ea521760572
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.doumee.core.utils;
 
import java.util.regex.Pattern;
 
/**
 * Java正则校验密码至少包含:字母数字特殊符号中的2种
 */
public class PwdCheckUtil {
 
    /**
     * 假定设置密码时,密码规则为:  字母、数字、特殊符号,至少匹配2种
     * 则密码可能出现的情况有:
     * 1、数字+特殊符号
     * 2、字母+特殊符号
     * 3、字母+数字
     * 4、字母+数字+特殊符号
     * (组合与顺序无关)
     * 解决思路:
     * 1、遍历字符串的字符数组,查看是否包含目标特殊字符,若包含,则标记字符串
     * 包含特殊字符,并替换当前特殊字符为''。
     * 2、判断剩下的字符组成的字符串,是否匹配以下情况
     * - 纯字母
     * - 纯数字
     * - 字母+数字
     * 3、字符串匹配规则
     * 纯字母+包含特殊字符  ---- 匹配通过
     * 纯数字+包含特殊字符 ---- 匹配通过
     * 字母+数字+包含个数字符 ---- 匹配通过
     */
    //特殊字符
    public static final String SPEC_CHARACTERS = " !\"#$%&'()*+,-./:;<=>?@\\]\\[^_`{|}~";
    // 纯字母
    public static final String character = "[a-zA-Z]{1,}$";
    // 纯数字
    public static final String numberic = "[0-9]{1,}$";
    // 字母和数字
    public static final String number_and_character = "((^[a-zA-Z]{1,}[0-9]{1,}[a-zA-Z0-9]*)+)" +
            "|((^[0-9]{1,}[a-zA-Z]{1,}[a-zA-Z0-9]*)+)$";
    // 字母或数字
    public static final String number_or_character = "[a-zA-Z0-9]+$";
    // 字母数字下划线
    public static final String ncw = "\\w+$";
 
    public static boolean checkPassword(String targetString) {
        String opStr = targetString;
        boolean isLegal = false;
        boolean hasSpecChar = false;
        char[] charArray = opStr.toCharArray();
        for (char c : charArray) {
            if (SPEC_CHARACTERS.contains(String.valueOf(c))) {
                hasSpecChar = true;
                // 替换此字符串
                opStr = opStr.replace(c, ' ');
            }
        }
        String excSpecCharStr = opStr.replace(" ", "");
        boolean isPureNum = Pattern.compile(numberic).matcher(excSpecCharStr).matches();
        boolean isPureChar = Pattern.compile(character).matcher(excSpecCharStr).matches();
        boolean isNumAndChar = Pattern.compile(number_and_character).matcher(excSpecCharStr).matches();
        isLegal = ((isPureNum && hasSpecChar)
                || (isPureChar && hasSpecChar) || isNumAndChar && hasSpecChar) || isNumAndChar;
        System.out.println("字符串:" + targetString + ",是否符合规则:" + isLegal);
        System.out.println("---------------");
        return isLegal;
    }
 
    public static void main(String[] args) {
        checkPassword("123456a");
//        checkPassword("41234123");
//        checkPassword("#$%^&&*(");
//        checkPassword("fasd$$");
//        checkPassword("41234%%%");
//        checkPassword("fasd41^(324");
//        checkPassword("fa413%^&*");
//        checkPassword("&%fa413%^&*");
    }
 
}