正则表达式验证具有字符限制的密码 [英] Regex to validate passwords with characters restrictions
问题描述
我需要使用以下规则验证密码:
I need to validate a password with these rules:
- 6 到 20 个字符
- 必须包含至少一位数字;
- 必须至少包含一个字母(不区分大小写);
- 可以包含以下字符:!@#$%&*
以下表达式匹配除最后一个要求之外的所有要求.我可以用最后一个做什么?
The following expression matches all but the last requirement. What can I do with the last one?
((?=.*d)(?=.*[A-z]).{6,20})
推荐答案
我不完全确定我有这个权利,但因为你的最后一个要求是可以包含以下字符:!@#$%&*" 我假设不允许使用其他特殊字符.换句话说,唯一允许的字符是字母、数字和特殊字符 !@#$%&*.
I'm not completely sure I have this right, but since your last requirement is "Can contain the following characters: !@#$%&*" I am assuming that other special characters are not allowed. In other words, the only allowed characters are letters, digits, and the special characters !@#$%&*.
如果这是正确的解释,下面的正则表达式应该可以工作:
If this is the correct interpretation, the following regex should work:
^((?=.*d)(?=.*[a-zA-Z])[a-zA-Z0-9!@#$%&*]{6,20})$
请注意,我将您的字符类 [Az]
更改为 [a-zA-Z]
,因为 [Az]
还将包括以下字符:[]^_`
Note that I changed your character class [A-z]
to [a-zA-Z]
, because [A-z]
will also include the following characters: []^_`
我还添加了字符串锚点的开头和结尾,以确保您不会得到部分匹配.
I also added beginning and end of string anchors to make sure you don't get a partial match.
这篇关于正则表达式验证具有字符限制的密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!