We have password requirements:
- Must contain capital letters
- Must contain lowercase letters
- Must contain numbers
- Must contain special characters
- There should be no characters repeating one after another
Now our validation regex is:
^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&*]))
So it doesn't validating the 5th requirement.
How to improve regex to validate characters repeating?
CodePudding user response:
You can remove the outer capture group, and then use a negative lookahead with a backreference to group 1 to exclude 2 repeating characters on after another.
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&*])(?!.*(.)\1)
In Java
String regex = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&*])(?!.*(.)\\1)";
Note that if using the pattern only for a password validation, the minimum length is just 4 characters.
To reduce some backtracking, you could also use negation:
^(?=[^\r\n\d]*\d)(?=[^\r\na-z]*[a-z])(?=[^\r\nA-Z]*[A-Z])(?=[^\r\n!@#$%&*]*[!@#$%&*])(?!.*(.)\1)