强制执行复杂密码的正则表达式,匹配 4 条规则中的 3 条 [英] Regular expression to enforce complex passwords, matching 3 out of 4 rules
问题描述
我有以下标准来为符合以下规则的密码创建正则表达式:
I have the following criteria for creating a regular expression for a password that conforms to the following rules:
- 密码长度必须为 8 个字符(我可以这样做:-)).
密码必须包含以下 4 条规则中至少 3 条的字符:
The password must then contain characters from at least 3 of the following 4 rules:
- 大写
- 小写
- 数字
- 非字母数字
我可以使用以下表达式使表达式匹配所有这些规则:
I can make the expression match ALL of those rules with the following expression:
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.[\W]).{8,}$/
但我正在努力解决如何做到这一点,只需要解决 4 条规则中的任何 3 条.
But I am struggling with how to do this in such a way that it only needs to solve any 3 of the 4 rules.
谁能帮我解决这个问题?
Can anyone help me out with this?
推荐答案
然后不要使用一个正则表达式来检查它.
Don't use one regex to check it then.
if (password.length < 8)
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)
alert("bad password");
<小时>
如果您必须使用单个正则表达式:
If you must use a single regex:
^(?:(?=.*[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
和一些因式分解构造而成.细分:
This regex is not optimized for efficiency. It is constructed by A·B·C + A·B·D + A·C·D + B·C·D
with some factorization. Breakdown:
^
(?:
(?=.*[a-z]) # 1. there is a lower-case letter ahead,
(?: # and
(?=.*[A-Z]) # 1.a.i) there is also an upper-case letter, and
(?=.*[\d\W]) # 1.a.ii) a number (\d) or symbol (\W),
| # or
(?=.*\W) # 1.b.i) there is a symbol, and
(?=.*\d) # 1.b.ii) a number ahead
)
| # OR
(?=.*\W) # 2.a) there is a symbol, and
(?=.*[A-Z]) # 2.b) an upper-case letter, and
(?=.*\d) # 2.c) a number ahead.
)
.{8,} # the password must be at least 8 characters long.
$
这篇关于强制执行复杂密码的正则表达式,匹配 4 条规则中的 3 条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!