正则表达式:“密码必须至少具有以下 4 个中的 3 个"; [英] Regex: "password must have at least 3 of the 4 of the following"

查看:17
本文介绍了正则表达式:“密码必须至少具有以下 4 个中的 3 个";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Regex 新手,到目前为止,我只将它用于简单的事情,例如必须是数字或字母".现在我必须做一些更复杂的事情.

I'm a Regex newbie, and so far have only used it for simple things, like "must be a number or letter". Now I have to do something a bit more complex.

我需要用它来验证一个密码,密码必须是8-16个字符,无控制/非打印/非ASCII字符,并且至少要有以下三个:

I need to use it to validate a password, which must be 8-16 characters, free of control/non-printing/non-ASCII characters, and must have at least three of the following:

  • 一个大写字母
  • 一个小写字母
  • 一个数字 0-9
  • 一个符号字符($、%、& 等)

我在想我要做的就是写一些类似一个大写字母,小写字母和数字,或者一个大写字母,小写字母和一个符号,或者一个大写字母,一个数字或一个符号,或者...."来涵盖所有可能的4 种中的 3 种"组合,但这似乎太过分了.有没有更简单的解决方案?

I'm thinking what I have to do is write something like "one capital letter, lowercase letter and number, OR one capital letter, lowercase letter and one symbol, OR one capital letter, one number or one symbol, OR...." to cover all possible "3 out of 4" combinations, but that seems excessive. Is there a simpler solution?

推荐答案

正确的做法是分别检查所有五个条件.但是,我认为你想要一个正则表达式是有原因的,你去吧:

The correct way to do this is to check all of the five conditions separately. However, I assume there is a reason you want a regex, here you go:

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

解释:

  • 我们想要匹配整个东西,因此我们用 ^$
  • 包围它
  • .{n,m} 匹配 nm 字符(在我们的例子中是 8 和 16).
  • 检查字符串是否包含某些内容而不实际匹配的一般方法是使用正向前瞻 (?=.*X),其中 X 是你想检查的东西.例如,如果您想确保字符串包含小写字母,您可以执行 (?=.*[a-z]).
  • 如果要检查一个字符串是否包含 XYZ,但没有实际匹配它们,可以使用前面的通过附加三个前瞻 (?=.*X)(?=.*Y)(?=.*Z)
  • 我们使用上述来匹配所提到的四件事中的三件事.我们用 |(or) 遍历所有可能的组合 - cCD|cDS|CDS|CcS (c = 小写字母, C = 大写字母,D = 数字,S = 特殊)
  • We want to match the whole thing, hence we surround it with ^$
  • .{n,m} matches between n and m characters (8 and 16 in our case).
  • The general way you can check if a string contains something, without actually matching it is by using positive lookahead (?=.*X), where X is the thing you want to check. For example, if you want to make sure the string contains a lowercase letter you can do (?=.*[a-z]).
  • If you want to check if a string contains X, Y and Z, but without actually matching them, you can use the previous recipe by appending the three lookaheads (?=.*X)(?=.*Y)(?=.*Z)
  • We use the above to match three of the four things mentioned. We go through all possible combinations with |(or) - cCD|cDS|CDS|CcS (c = lowercase letter, C = capital letter, D = digit, S = special)

查看实际操作

这篇关于正则表达式:“密码必须至少具有以下 4 个中的 3 个";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆