我如何要求一个正则表达式中至少有两个前瞻模式匹配? [英] How can I require that at least two lookahead patterns match within one regex?

查看:103
本文介绍了我如何要求一个正则表达式中至少有两个前瞻模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下正则表达式可确保密码至少包含一个小写字母,一个大写字母,一个数字和一个特殊字符:

The following regex ensures a password contains at least one lowercase, one uppercase, one number, and one special character:

^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^a-zA-Z0-9\s]).*$

那行得通.在此基础上,我希望仅满足这些组中的两个才能使密码有效.

That works. Building on this, I'd like to require that only two of these groups be fulfilled in order for a password to be valid.

例如,这些将是有效的密码:aaaaa5,BFEWREWRE77,#2ccc.

For example, these would be valid passwords: aaaaa5, BFEWREWRE77, #2ccc.

我是否可以修改此正则表达式以支持此要求?

Is there I way I can modify this regex to support this requirement?

推荐答案

您可以这样做:

禁止使用空格

^(?=([A-Z]+|[a-z]+|[0-9]+|[^a-zA-Z0-9\s]+))\1\S+$

允许使用空格:

^\s*(?=((?:[A-Z]+\s*)+|(?:[a-z]+\s*)+|(?:[0-9]+\s*)+|(?:[^a-zA-Z0-9\s]+\s*)+))\1.+$

说明:

(?=([A-Z]+|[a-z]+|[0-9]+|[^a-zA-Z0-9\s]+))\1模拟原子组 (?>[A-Z]+|[a-z]+|[0-9]+|[^a-zA-Z0-9\s]+).因此,一旦匹配了该组的一个分支,就不再允许正则表达式引擎在匹配的字符内回溯.

(?=([A-Z]+|[a-z]+|[0-9]+|[^a-zA-Z0-9\s]+))\1 emulates the atomic group (?>[A-Z]+|[a-z]+|[0-9]+|[^a-zA-Z0-9\s]+). So once a branch of this group is matched, the regex engine is no more allowed to backtrack inside the matched characters.

由于默认情况下量词是贪婪的,因此其中一个类别的所有字符都被原子组匹配.

Since the quantifiers are greedy by default, all the characters of one of the categories are matched by the atomic group.

\S.匹配的下一个字符显然来自与该组中使用的字符不同的字符类.

The next character matched by \S or . is obviously from a different character class than the one used in the group.

注意:对于第二种模式,由于对字符串中使用的字符没有限制,因此无需测试字符串,直到结尾为止,因此可以编写:

Note: for the second pattern, since there is no limitation about the characters used in the string, you don't need to test the string until the end, so you can write:

^\s*(?=((?:[A-Z]+\s*)+|(?:[a-z]+\s*)+|(?:[0-9]+\s*)+|(?:[^a-zA-Z0-9\s]+\s*)+))\1.

这篇关于我如何要求一个正则表达式中至少有两个前瞻模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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