Skip to main content
 首页 » 编程设计

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

2024年06月20日25TianFang

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

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

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

  1. 大写
  2. 小写
  3. 数字
  4. 非字母数字

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

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

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

谁能帮我解决这个问题吗?

请您参考如下方法:

不要使用一个正则表达式来检查它。

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"); 
<小时 />

如果您必须使用单个正则表达式:

^(?:(?=.*[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 构建的进行一些因式分解。分割:

^ 
(?: 
    (?=.*[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. 
$