正则表达式匹配 m 组中的至少 n 个
我打算编写一个正则表达式,仅当字符串包含至少 n 个不同类别的字符时才匹配。我打算用它来强制我的用户创建强密码,并希望检查密码是否至少包含以下 3 个内容:
- 字符
- 大写字符
- 数字
- 特殊字符
如果所有这些类都存在,则编写一个匹配的正则表达式是微不足道的使用前瞻。但是,我无法理解“至少 3”部分。这是否可能(以一个漂亮、紧凑的表达式)或者我必须创建一个怪物表达式?
I was going to write a regular expression that would match only if a string contains at least n different classes of characters. I was going to use this to force my users to create strong passwords and wanted to check if the password contains at least 3 of the following:
- Characters
- Capital Characters
- Numbers
- Special Characters
Writing a regular expression that matches if all of those classes are present is trivial using lookaheads. However, I cannot wrap my head around the "at least 3" part. Is this even possible (in a nice, compact expression) or would I have to create a monster expression?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这比列出 4 个字符中的 3 个的每种可能组合更紧凑。它利用负向前视来确保整个字符串不仅仅由您列出的一个或两个字符类组成:
按顺序,此处的组是:
如果整个字符串(因为
$ 负数Lookahead)仅包含来自上述任何组的字符。
I think this will be more compact than listing each possible combination of 3 of the 4. It utilizes negative lookahead to make sure that the entire string is not composed of only one or two of the character classes you listed:
In order, the groups here are:
This regex will fail if the entire string (because of the
$
in the negative lookahead) contains only characters from any of the above groups.您必须为 4 个中的 3 个(总共四个表达式)的每种可能组合编写一个表达式,然后 |将各个表达式组合在一起,如果它们满足至少一个原始表达式,则它们通过。
You have to write an expression for each possible combination of 3 of the 4 (four expressions in total), and then | the individual expressions together so that they pass if they fulfill at least one of the original expressions.
您对此解决方案有何看法?
您可以使用 4 个小型 RE,而不是使用 1 个类似怪物的表情。然后使用变量
countGroups
,其中包含已映射字符组的数量。我希望它有帮助
What do you think about this solution?
Instead of using 1 monster-like expression you can use 4 small RE. And then work with variable
countGroups
, which contains number of maеched character groups.I hope it is helpfull