0

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?

2
  • Honestly, wouldn't this be easier and more readable with a loop? Commented Feb 3, 2023 at 12:57
  • We are using it for validating HTTP method body with @Pattern annotation on the field Commented Feb 3, 2023 at 15:12

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.