正则表达式以验证具有字符限制的密码 [英] 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})$
请注意,我将字符类[A-z]
更改为[a-zA-Z]
,因为[A-z]
还将包含以下字符:[\] ^ _`
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屋!