Home > other >  Java password validation regex
Java password validation regex

Time:02-03

We have password requirements:

  1. Must contain capital letters
  2. Must contain lowercase letters
  3. Must contain numbers
  4. Must contain special characters
  5. 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)";

Regex demo

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)

Regex demo

  • Related