正则表达式以强制执行复杂密码,匹配4个规则中的3个

正则表达式以强制执行复杂密码,匹配4个规则中的3个

我有以下标准为密码创建符合以下规则的正则表达式:

  1. 密码长度必须为8个字符(我可以这样做:-))。

然后,密码必须包含以下4条规则中至少3条的字符:

  1. 大写

  2. 小写

  3. 数字

  4. 非字母数字

我可以使表达式与所有这些规则匹配,并使用以下表达式:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.[\W]).{8,}$/

但我正在努力解决如何以这样的方式做到这一点,它只需要解决4条规则中的任何3条。

任何人都可以帮我解决这个问题吗?


小怪兽爱吃肉
浏览 1224回答 3
3回答

侃侃无极

然后不要使用一个正则表达式进行检查。if (password.length < 8)&nbsp; alert("bad password");var hasUpperCase = /[A-Z]/.test(password);var hasLowerCase = /[a-z]/.test(password);var hasNumbers = /\d/.test(password);var hasNonalphas = /\W/.test(password);if (hasUpperCase + hasLowerCase + hasNumbers + hasNonalphas < 3)&nbsp; alert("bad password");如果必须使用单个正则表达式:^(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}$此正则表达式未针对效率进行优化。它是通过A·B·C + A·B·D + A·C·D + B·C·D一些因子分解构建的。分解:^(?:&nbsp; &nbsp; (?=.*[a-z])&nbsp; &nbsp; &nbsp; &nbsp;# 1. there is a lower-case letter ahead,&nbsp; &nbsp; (?:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#&nbsp; &nbsp; and&nbsp; &nbsp; &nbsp; &nbsp; (?=.*[A-Z])&nbsp; &nbsp;#&nbsp; &nbsp; &nbsp;1.a.i) there is also an upper-case letter, and&nbsp; &nbsp; &nbsp; &nbsp; (?=.*[\d\W])&nbsp; #&nbsp; &nbsp; &nbsp;1.a.ii) a number (\d) or symbol (\W),&nbsp; &nbsp; |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#&nbsp; &nbsp; or&nbsp; &nbsp; &nbsp; &nbsp; (?=.*\W)&nbsp; &nbsp; &nbsp; #&nbsp; &nbsp; &nbsp;1.b.i) there is a symbol, and&nbsp; &nbsp; &nbsp; &nbsp; (?=.*\d)&nbsp; &nbsp; &nbsp; #&nbsp; &nbsp; &nbsp;1.b.ii) a number ahead&nbsp; &nbsp; )|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# OR&nbsp; &nbsp; (?=.*\W)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # 2.a) there is a symbol, and&nbsp; &nbsp; (?=.*[A-Z])&nbsp; &nbsp; &nbsp; &nbsp;# 2.b) an upper-case letter, and&nbsp; &nbsp; (?=.*\d)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # 2.c) a number ahead.).{8,}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# the password must be at least 8 characters long.$

慕后森

你可以编写一个非常复杂的正则表达式来做到这一点。相反,我建议写四个不同的正则表达式,每个规则一个,并逐个测试它们,计算它们中有多少匹配。如果有四分之三,请接受密码。

蛊毒传说

您可以使用以下正则表达式:(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$)?(^(?=.*\d)(?=.*[a-z])(?=.*[@#$%^&+=]).*$)?(^(?=.*\d)(?=.*[A-Z])(?=.*[@#$%^&+=]).*$)?(^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$)?密码最小长度为8,最大长度为32,您可以使用以下正则表达式:(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,32}$)?(^(?=.*\d)(?=.*[a-z])(?=.*[@#$%^&+=]).{8,32}$)?(^(?=.*\d)(?=.*[A-Z])(?=.*[@#$%^&+=]).{8,32}$)?(^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).{8,32}$)?
打开App,查看更多内容
随时随地看视频慕课网APP