密码至少包含 1 个大写 1 个小写 1 个数字 1 个特殊字符,长度至少为 10

由于字符/数字可以在字符串中的任何位置,我们需要前瞻。前瞻是 zero width 意味着他们不消耗任何字符串。简单来说,在每个先行条件满足后,检查的位置重置到原始位置。

假设 : - 将非单词字符视为特殊字符

^(?=.{10,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*\W).*$

在继续解释之前,让我们来看看字符串 1$d%aA 上的正则表达式如何工作( 这里不考虑长度

StackOverflow 文档

图片来源 : - https://regex101.com/

值得注意的事情

  • 由于锚标记^,从字符串的开头开始检查。
  • 在前瞻条件满足后,检查位置被重置为启动。

正则表达式细分

^ #Starting of string
 (?=.{10,}$) #Check there is at least 10 characters in the string. 
             #As this is lookahead the position of checking will reset to starting again
 (?=.*[a-z]) #Check if there is at least one lowercase in string.
             #As this is lookahead the position of checking will reset to starting again
 (?=.*[A-Z]) #Check if there is at least one uppercase in string.
             #As this is lookahead the position of checking will reset to starting again
 (?=.*[0-9]) #Check if there is at least one digit in string.
             #As this is lookahead the position of checking will reset to starting again
 (?=.*\W) #Check if there is at least one special character in string.
          #As this is lookahead the position of checking will reset to starting again
.*$ #Capture the entire string if all the condition of lookahead is met. This is not required if only validation is needed

我们也可以使用上面的正则表达式的非贪婪版本

^(?=.{10,}$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?\W).*$