带字符、数字和标点符号的密码正则表达式。

4
我需要一个密码的正则表达式,其中条件如下:
1. 密码长度必须至少为7个字符,但不超过10个字符。 2. 密码必须包含至少一个大写字母、一个小写字母、一个数字和一个标点符号。(例如,a-z、A-Z、0-9、!@#$%^&*()_+|~-=`{}[]:";'<>?,./)
我尝试使用以下正则表达式:`^(?=.{7,10})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+|~={}:";'<>?,./-][])$`
但标点符号部分在解释时不够清楚,在 `http://regex101.com/` 测试时无法通过。
标点符号的解释似乎有问题,请有人帮忙解释并完善它。

1
你为什么要限制密码长度在10个字符以内?很多注重安全的人会选择12、14、16个或更长的密码。 - scunliffe
@scunliffe 很好的观点,谢谢您,我们会讨论您的观点。 - Suganthan
@Suganthan,由于您正在哈希(并且应该已经盐处理)密码,因此没有理由限制其上限字符约束。 - stuXnet
@stuXnet,我没有理解你的意思,请简要说明一下。 - Suganthan
@stuXnet 正如您所提到的,我们正在进行哈希处理并存储数据。 - Suganthan
显示剩余4条评论
5个回答

5
以下内容应该符合您的需求:
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()_+|~=`{}\[\]:";'<>?,./-]).{7,10}$

正则表达式可视化

Debuggex演示

在Java中,不要忘记转义反斜杠,因为它们是字符串文字。换句话说,将上面的正则表达式中的每个反斜杠替换为两个反斜杠。

如果您不想允许空格,请使用\S{7,10}简单替换.{7,10}(再次,在Java中转义反斜杠)。


你的正则表达式错误的两个原因:

  • 您没有转义您的标点类中的[]字符(语法错误);
  • 您必须将-字符放在字符类的开头或结尾。否则,它将被解释为特殊字符。例如,[A-Z]匹配AZ之间的任何大写字母,而[AZ-]匹配AZ-

对于测试字符串(1:- 78tre48`12,2:- yuuyuyuyuyuy,3:- ad8\\09+9),它实际上失败了。 - Suganthan
也许这是修正后的版本,请您检查一下我是否正确 /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()_+|~={}[]:";'<>?,./-]).{7,10}$/` - Suganthan
@Suganthan 在这些字符串中,你没有大写字母,而你要求密码必须至少包含一个大写字母 - sp00m
是的,你说得对,让我清楚地测试一下我的“测试字符串和我编写的代码”。 - Suganthan

0

我疯了,竟然写出了这个正则表达式:

为了简单易读,只需使用!@#作为特殊字符,您可以在!@#后添加其他字符:

^(?!\d+$)(?![a-z]+$)(?![A-Z]+$)(?![!@#]+$)(?![a-z\d]+$)(?![A-Z\d]+$)(?![!@#\d]+$)(?![a-zA-Z]+$)(?![!@#a-z]+$)(?![!@#A-Z]+$)(?![a-zA-Z\d]+$)(?![!@#a-z\d]+$)(?![!@#A-Z\d]+$)(?![!@#a-zA-Z]+$)[!@#a-zA-Z\d]{7,10}$

演示

^           
(?!\d+$)           // the password cannot be all digites,of course
(?![a-z]+$)        // the password cannot be all a-z
(?![A-Z]+$)        // the password cannot be all A-Z
(?![!@#]+$)        // the password cannot be all !@# 
(?![a-z\d]+$)      // the password cannot be all a-z 0-9
(?![A-Z\d]+$)      // the password cannot be all A-Z 0-9
(?![!@#\d]+$)      // the password cannot be all !@# 0-9
(?![a-zA-Z]+$)     // the password cannot be all A-Z a-z
(?![!@#a-z]+$)     // the password cannot be all !@# a-z
(?![!@#A-Z]+$)     // the password cannot be all !@# A-Z
(?![a-zA-Z\d]+$)   // the password cannot be all A-Z a-z 0-9
(?![!@#a-z\d]+$)   // the password cannot be all !@# a-z 0-9
(?![!@#A-Z\d]+$)   // the password cannot be all !@# A-Z
(?![!@#a-zA-Z]+$)  // the password cannot be all !@# a-z A-Z
[!@#a-zA-Z\d]{7,10}  // the password SHOULD be in `!@# a-z A-Z 0-9` and length 7-10
$

请解释一下,:O 是什么意思? :) - flotothemoon
1
@1337 更新我的解释。顺便说一句:为了方便阅读,请使用!@#作为特殊字符,您可以在!@#后面添加其他字符。 - Tim.Tang

0

检查这个

          ((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})

为了练习

           http://www.regexr.com/

1
为什么是{6,20}?OP指出:_密码必须至少有7个字符,但不能超过10个字符_。 - arco444
1
呀..这只是一个例子...第一个参数必须至少有6个字符,第二个参数不应超过20个字符,您可以相应地进行更改。 - Monis Majeed

0

这里也是一个很好的基础

([a-zA-Z0-9!@#$%^&*_+=(){}[\];':",\.<>\/\?-]{8,38})

另外,为了测试我喜欢使用https://regex101.com


0

你根本没有使用到你的字符串。添加

.* 

在最后进行消耗。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接