有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

允许的Java正则表达式用户特定字符

我试图使用正则表达式,只允许用户指定的给定密码

我试过了,但没用

^[a-zA-Z0-9@\\#$%&*()_+\\]\\[';:?.,!^-]{"+MIN_LENGTH+","+MAX_LENGTH+"}$

MIN_LENGTH和MAX_LENGTH是数据库中的最小和最大长度大小写,如何给出具体的大写、小写、数字和特殊字符

问候 普拉迪普


共 (1) 个答案

  1. # 1 楼答案

    恐怕正则表达式没有那么强大。您可能会找到一个使用单个正则表达式的解决方案,但它将完全无法读取和扩展。我建议您将每个约束逻辑分离为一个子区域。例如:

    public static boolean isPasswordValid(String password) {
        // 1 to 3 occurrences of lowercased chars
        if (!password.matches("(?:[^a-z]*[a-z]){1,3}[^a-z]*")) {
            return false;
        }
        // 2 to 4 occurrences of uppercased chars
        if (!password.matches("(?:[^A-Z]*[A-Z]){2,4}[^A-Z]*")) {
            return false;
        }
        // 3 to 5 occurrences of digits
        if (!password.matches("(?:[^0-9]*[0-9]){3,5}[^0-9]*")) {
            return false;
        }
        // 4 to 6 occurrences of special chars (simplified to "_", "." or "-")
        if (!password.matches("(?:[^_.-]*[_.-]){4,6}[^_.-]*")) {
            return false;
        }
        // no other kind of chars, and password length from 3 to 20
        if (!password.matches("[a-zA-Z0-9_.-]{3,20}")) {
            return false;
        }
        return true;
    }