我正在使用java.util.regex.Pattern来匹配符合以下条件的密码:
我有1& 2覆盖,但我想不出怎么做3。
1& 2 - [\\w]{7,}
有什么想法吗?
答案 0 :(得分:4)
你可以用它。这基本上使用lookahead来实现第三个要求。
(?=.*\d)(?=.*[a-zA-Z])\w{7,}
或Java字符串
"(?=.*\\d)(?=.*[a-zA-Z])\\w{7,}"
<强>解释强>
"(?=" + // Assert that the regex below can be matched, starting at this position (positive lookahead)
"." + // Match any single character
"*" + // Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
"\\d" + // Match a single digit 0..9
")" +
"(?=" + // Assert that the regex below can be matched, starting at this position (positive lookahead)
"." + // Match any single character
"*" + // Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
"[a-zA-Z]" + // Match a single character present in the list below
// A character in the range between “a” and “z”
// A character in the range between “A” and “Z”
")" +
"\\w" + // Match a single character that is a “word character” (letters, digits, and underscores)
"{7,}" // Between 7 and unlimited times, as many times as possible, giving back as needed (greedy)
修改强>
如果要包含unicode字母支持,请使用此
(?=.*\d)(?=.*\pL)[\pL\d]{7,}
答案 1 :(得分:4)
如果您需要更改密码凭据,那么只使用Regex执行此操作很容易变得错综复杂,很难理解/阅读。
而是在循环中迭代密码并计算不同类型的字符,然后进行简单的if-checks。
如(未经测试):
if (password.length() < 7) return false;
int countDigit = 0;
int countLetter = 0;
for (int i = 0; password.length(); i++) {
if (Character.isDigit(password.charAt(i)) {
countDigit++;
}
else if (Character.isLetter(password.charAt(i)) {
countLetter++;
}
}
if (countDigit == 0 || countLetter == 0) {
return false;
}
return true;
答案 2 :(得分:1)
使用\w
不需要字符类,它本身就是一个字符类。但是它也匹配你没有提到的下划线。因此,最好使用自定义字符类。
对于“至少一个”部分,请使用前瞻:
/(?=.*\d)(?=.*[A-Za-z])[A-Za-z0-9]{7,}/
您可能需要添加一些额外的转义以使其适用于Java *。
* ,遗憾的是我无法帮助!
答案 3 :(得分:1)
可能在一个正则表达式中执行此操作,但我不会因为它很难维护。
我会这样做:
if (pass.matches("[a-zA-Z0-9]{7,}") &&
pass.matches("[a-zA-Z]") &&
pass.matches("\\d"))
{
// password is OK
}
然后很明显如何对密码应用其他约束 - 它们只是添加了额外的&& ...
子句。
注意:我故意使用[a-z]
而不是\w
,因为如果您在其他字符可能会被视为“字母”的替代语言环境中使用它,我不确定\w
会发生什么”
答案 4 :(得分:0)
我会添加另一个正则表达式来覆盖第三个标准(你不必将它们全部固定在一个正则表达式中,但可能想要将它们组合起来)。我会选择像^(?=.*\d)(?=.*[a-zA-Z])
取自这里 - http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/