Regular expression for password (at least 2 digits and one special character and minimum length 8)

后端 未结 6 1470
情歌与酒
情歌与酒 2020-11-30 06:27

I have been searching for regular expression which accepts at least two digits and one special character and minimum password length is 8. So far I have done the following:

6条回答
  •  借酒劲吻你
    2020-11-30 06:47

    Something like this should do the trick.

    ^(?=(.*\d){2})(?=.*[a-zA-Z])(?=.*[!@#$%])[0-9a-zA-Z!@#$%]{8,}
    
    (?=(.*\d){2}) - uses lookahead (?=) and says the password must contain at least 2 digits
    
    (?=.*[a-zA-Z]) - uses lookahead and says the password must contain an alpha
    
    (?=.*[!@#$%]) - uses lookahead and says the password must contain 1 or more special characters which are defined
    
    [0-9a-zA-Z!@#$%] - dictates the allowed characters
    
    {8,} - says the password must be at least 8 characters long
    

    It might need a little tweaking e.g. specifying exactly which special characters you need but it should do the trick.

提交回复
热议问题