我写了一个正则表达式来根据以下条件验证密码。
Your password length should be 8 to 20 and must contain at least 2 letters, 1 number and 1 special character. Space not allowed
我的正则表达式是-
final String PASSWORD_PATTERN =
"^(?=.*[0-9].{1})(?=.*[A-Za-z].{2})(?=.*[@#$%^&+=].{1})(?=\\S+$).{8,}$";
它在所有其他情况下都有效,除非我在字符串末尾输入任何特殊字符。请有人建议我在做什么错?
最佳答案
如果不喜欢使用正则表达式,可以编写一个函数来遍历字符串并计算数字、字母或特殊字符的数量。
boolean isValidPassword(char[] pass) {
int letters = 0, digits = 0, specialChars = 0;
if (pass.length < 8 || pass.length > 20) {
return false;
}
for (int i = 0; i < pass.length; i++) {
char ch = pass[i];
if (Character.isLetter(ch)) {
letters++;
}
else if (Character.isDigit(ch)) {
digits++;
}
else if (isSpecialChar(ch)) {
specialChars++;
}
else if (Character.isWhiteSpace(ch)) {
return false;
}
}
return !(letters < 2 || digits < 1 || specialChars < 1);
}
static boolean isSpecialChar(char c) {
switch (c) {
case '@':
case '#':
case '$':
case '%':
case '^':
case '&':
case '+':
case '=':
return true;
default:
return false;
}
}
请注意,这也解决了使用 String
时的安全问题,如 this article 所述和 this question .
关于java - 密码验证不允许在屏幕末尾出现特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34942151/