用于密码匹配的正则表达式

时间:2013-05-13 17:45:26

标签: java regex

我搜索过该网站并没有找到我想要的内容。 密码标准:

  1. 必须是6个字符,最多50个
  2. 必须包含1个字母字符
  3. 必须包含1个数字或特殊字符
  4. 以下是我在java中的内容:

    public static Pattern p = Pattern.compile(
     "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])|(?=.*[\\d~!@#$%^&*\\(\\)_+\\{\\}\\[\\]\\?<>|_]).{6,50})"
    );
    

    问题是密码1234567是匹配的(有效),它不应该是。

    任何帮助都会很棒。

6 个答案:

答案 0 :(得分:5)

我不会尝试使用单个正则表达式来执行此操作。当正则表达式变得冗长复杂时,它们往往表现不佳。

boolean valid(String password){
    return password != null &&
    password.length() >= 6 &&
    password.length() <= 50 &&
    password.matches(".*[A-Za-z].*") &&
    password.matches(".*[0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_+\\{\\}\\[\\]\\?<>|_].*");
}

答案 1 :(得分:1)

正则表达式只能匹配可以表示为确定性有限自动机的语言,即不需要内存的语言。由于您必须计算特殊字符和字母字符,因此这需要内存,因此您无法在DFA中执行此操作。您的规则很简单,但您可以只扫描密码,确定其长度并确保所需的字符可用。

答案 2 :(得分:1)

我建议你分开字符和长度验证:

boolean checkPassword(String password) {
    return password.length() >= 6 && password.length() <= 50 && Pattern.compile("\\d|\\w").matcher(password).find();
}

答案 3 :(得分:0)

我建议拆分成单独的正则表达式

$re_numbers = "/[0-9]/";
$re_letters = "/[a-zA-Z]/";

它们都必须匹配,长度也要单独测试。 代码看起来更清晰,更易于理解/更改。

答案 4 :(得分:0)

对于这么简单的任务来说,这太复杂了:

使用String#length()

验证长度
password.length() >= 6 && password.length() <= 50

使用Matcher#find()

验证每个组
Pattern alpha = Pattern.compile("[a-zA-Z]");
boolean hasAlpha = alpha.matcher(password).find();
Pattern digit = Pattern.compile("\d");
boolean hasDigit = digit.matcher(password).find();
Pattern special = Pattern.compile("[\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_+\\{\\}\\[\\]\\?<>|_]");
boolean hasSpecial = special.matcher(password).find();

答案 5 :(得分:0)

确保使用Matcher.matches()方法,该方法断言整个字符串与模式匹配。

您当前的正则表达式:

"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])|(?=.*[\\d~!@#$%^&*\\(\\)_+\\{\\}\\[\\]\\?<>|_]).{6,50})"

表示:

  • 该字符串必须至少包含数字(?=.*\\d),小写英文字母(?=.*[a-z])和大写字母(?=.*[A-Z])
  • OR |字符串必须包含至少1个字符,可以是数字或特殊字符(?=.*[\\d~!@#$%^&*\\(\\)_+\\{\\}\\[\\]\\?<>|_])
  • 上述条件均为true,字符串长度必须介于6到50个字符之间,并且不包含任何行分隔符。

正确的正则表达式是:

"(?=.*[a-zA-Z])(?=.*[\\d~!@#$%^&*()_+{}\\[\\]?<>|]).{6,50}"

这将检查:

  • 该字符串必须包含英文字母字符(大写或小写)(?=.*[a-zA-Z]),以及可以是数字或特殊字符的字符(?=.*[\\d~!@#$%^&*()_+{}\\[\\]?<>|])
  • 字符串必须介于6到50个字符之间,并且不包含任何行分隔符。

请注意,除了[]之外,我删除了大多数字符的转义,因为{}?()在字符类中失去了它们的特殊含义。

相关问题