试试这个:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{8,}$
解释:
^ # start-of-string
(?=.*[0-9]) # a digit must occur at least once
(?=.*[a-z]) # a lower case letter must occur at least once
(?=.*[A-Z]) # an upper case letter must occur at least once
(?=.*[@#$%^&+=]) # a special character must occur at least once
(?=\S+$) # no whitespace allowed in the entire string
.{8,} # anything, at least eight places though
$ # end-of-string
添加、修改或删除单个规则很容易,因为每个规则都是一个独立的“模块”。
构造会吃掉整个字符串 (),并回溯到可以匹配的第一个匹配项。如果找到,它将成功,否则它将失败。(?=.*[xyz])
.*
[xyz]
[xyz]
另一种方法是使用不情愿的限定符:。对于密码检查,这几乎没有任何区别,对于更长的字符串,它可能是更有效的变体。(?=.*?[xyz])
当然,最有效的变体(但最难阅读和维护,因此最容易出错)是。对于这种长度的正则表达式和目的,我不建议这样做,因为它没有真正的好处。(?=[^xyz]*[xyz])