Regex For Passwords
As much as regex can be a great mental exercise it can also be a bit of a nightmare if its a complicated one. SO here is a breakdown of a regex thats of a medium difficulty and also fun.
The following regex should match a password that contains at least 8 characters, one uppercase letter, one number, and one special character:
^(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()_+-=\[\]{};':"\\|,.<>\/?]).{8,}$
This expression uses several positive lookahead assertions to ensure that the password contains the required characters, and it also requires that the password must be at least 8 characters long.
Here's a breakdown of the expression:
^
: This anchors the expression to the start of the string.(?=.*[A-Z])
: This is a positive lookahead assertion that requires the password to contain at least one uppercase letter. The.*
matches any character (except a newline), and the[A-Z]
matches any uppercase letter.(?=.*[0-9])
: This is a positive lookahead assertion that requires the password to contain at least one number. The.*
matches any character (except a newline), and the[0-9]
matches any digit.(?=.*[!@#$%^&*()_+-=\[\]{};':"\\|,.<>\/?])
: This is a positive lookahead assertion that requires the password to contain at least one special character. The.*
matches any character (except a newline), and the[!@#$%^&*()_+-=\[\]{};':"\\|,.<>\/?]
matches any of the specified special characters..{8,}
: This matches any character (except a newline) that occurs 8 or more times. This ensures that the password is at least 8 characters long.$
: This anchors the expression to the end of the string.
This regular expression is fairly strict and will only match passwords that contain all of the required characters and are at least 8 characters long. If you want to allow for more flexibility, you can make some of the assertions optional by using the ?
character. For example, to allow for passwords that may or may not contain a special character, you could use this expression:
^(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()_+-=\[\]{};':"\\|,.<>\/?])?.{8,}$
This expression still requires the password to contain at least one uppercase letter and one number, but it allows for the possibility that the password may not contain special character.