【发布时间】:2013-10-21 10:11:15
【问题描述】:
我一直在寻找至少接受两位数字和一个特殊字符且最小密码长度为 8 的正则表达式。到目前为止,我已经完成了以下操作:[0-9a-zA-Z!@#$%0-9]*[!@#$%0-9]+[0-9a-zA-Z!@#$%0-9]*
【问题讨论】:
标签: regex
我一直在寻找至少接受两位数字和一个特殊字符且最小密码长度为 8 的正则表达式。到目前为止,我已经完成了以下操作:[0-9a-zA-Z!@#$%0-9]*[!@#$%0-9]+[0-9a-zA-Z!@#$%0-9]*
【问题讨论】:
标签: regex
试试这个:
^(?=.*\d{2,})(?=.*[$-/:-?{-~!"^_`\[\]]{1,})(?=.*\w).{8,}$
下面是它的工作原理:
(?=.*\d{2,})这部分说除了至少2位数字(?=.*[$-/:-?{-~!"^_[]]{1,})` 这些是特殊字符,至少 1(?=.*\w) 和其余是任何字母(等于[A-Za-z0-9_]).{8,}$ 这个至少包含 8 个字符,包括所有以前的规则。
下面是当前正则表达式的映射(在Regexper 的帮助下制作)
更新
正则表达式应该看起来像这样^(?=(.*\d){2,})(?=.*[$-\/:-?{-~!"^_'\[\]]{1,})(?=.*\w).{8,}$
查看 cmets 了解更多详情。
【讨论】:
(?=(.*\d){2,})。像这样的正则表达式^(?=(.*\d){2,})(?=.*[$-\/:-?{-~!"^_'\[\]]{1,})(?=.*\w).{8,}$。感谢您的留言。
试试这个正则表达式。它使用前瞻来验证至少有两位数字和您列出的特殊字符之一。
^(?=.*?[0-9].*?[0-9])(?=.*[!@#$%])[0-9a-zA-Z!@#$%0-9]{8,}$
解释
^ #Match start of line.
(?=.*?[0-9].*?[0-9]) #Look ahead and see if you can find at least two digits. Expression will fail if not.
(?=.*[!@#$%]) #Look ahead and see if you can find at least one of the character in bracket []. Expression will fail if not.
[0-9a-zA-Z!@#$%0-9]{8,} #Match at least 8 of the characters inside bracket [] to be successful.
$ # Match end of line.
【讨论】:
这样的事情应该可以解决问题。
^(?=(.*\d){2})(?=.*[a-zA-Z])(?=.*[!@#$%])[0-9a-zA-Z!@#$%]{8,}
(?=(.*\d){2}) - uses lookahead (?=) and says the password must contain at least 2 digits
(?=.*[a-zA-Z]) - uses lookahead and says the password must contain an alpha
(?=.*[!@#$%]) - uses lookahead and says the password must contain 1 or more special characters which are defined
[0-9a-zA-Z!@#$%] - dictates the allowed characters
{8,} - says the password must be at least 8 characters long
它可能需要一些调整,例如准确指定您需要的特殊字符,但它应该可以解决问题。
【讨论】:
试试这个:^.*(?=.{8,15})(?=.*\d)(?=.*\d)[a-zA-Z0-9!@#$%]+$
请阅读以下链接以制定密码正则表达式策略:-
【讨论】:
无论如何,都没有理由在单个正则表达式中实现所有规则。 考虑这样做:
Pattern[] pwdrules = new Pattern[] {
Pattern.compile("........"), // at least 8 chars
Pattern.compile("\d.*\d"), // 2 digits
Pattern.compile("[-!"§$%&/()=?+*~#'_:.,;]") // 1 special char
}
String password = ......;
boolean passed = true;
for (Pattern p : pwdrules) {
Matcher m = p.matcher(password);
if (m.find()) continue;
System.err.println("Rule " + p + " violated.");
passed = false;
}
if (passed) { .. ok case.. }
else { .. not ok case ... }
这有一个额外的好处,即可以毫不费力地添加、删除或更改密码规则。它们甚至可以驻留在某个资源文件中。
此外,它更具可读性。
【讨论】:
正则表达式在您要匹配的字符串上定义一个结构。除非您在正则表达式上定义空间结构(例如至少两位数字后跟一个特殊字符,然后是 ...),否则您不能使用 regex 来验证您的字符串。
【讨论】: