正则表达式将强密码与两个或多个特殊字符匹配 [英] Regex match a strong password with two or more special characters
问题描述
我需要使用具有以下要求的javascript来匹配密码字段:
I need to regex match a password field using javascript with the following requirements:
- 至少15个字符
- 两个或多个小写字母
- 两个或更多大写字母
- 两个或更多个数字
- 以下两个或多个特殊字符:!@#$%^& * -
- At least 15 characters
- two or more lower case letters
- two or more upper case letters
- two or more digits
- two or more of the following special characters: !@#$%^&*-
我有正则表达式照顾大多数情况:
I have a regex that takes care of MOST cases:
/^.*(?=.{15,})(?=.{2,}\d)(?=.{2,}[a-z])(?=.{2,}[A-Z])(?=.{2,}[\!\@\#\$\%\^\&\*\-]).*$/
这里的问题是符号,它适用于:
The problem here is with the symbols, it works with:
P@ssw0rdP@ssw0rd
Pssw0rdPssw0rd@@
Pssw0rd@@Pssw0rd
但不是:
@@Pssw0rdPssw0rd
我有一个随机密码生成器设置彻底测试这个,所以任何想法都非常感激。谢谢!
I have a random password generator set up to exhaustively test this, so any ideas are greatly appreciated. Thanks!
推荐答案
/^(?=(?:.*[a-z]){2})(?=(?:.*[A-Z]){2})(?=(?:.*\d){2})(?=(?:.*[!@#$%^&*-]){2}).{15,}$/
你的前瞻是错误的。模式
Your lookaheads are wrong. The pattern
(?=.{2,}[class])
表示匹配2个或更多字符(无论是什么字符),然后是所需类别的1个字符。这与您指定的所需类的2个或更多字符完全不同。
means to match 2 or more characters (no matter what characters), then followed by 1 character of the desired class. This is entirely different from "2 or more character of the desired class" you specified.
要正确测试文本中是否包含所需类的字符,请使用
To correctly test if a character of desired class is in the text, use
(?=.*[class])
因为你要检查两次,重复模式
and since you want to check it twice, repeat the pattern
(?=.*[class].*[class])
# equivalent to (?=(?:.*[class]){2})
这篇关于正则表达式将强密码与两个或多个特殊字符匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!