A B
A B

Reputation: 1936

Java regex for consecutively repeated letters, numbers and special characters

I have to apply a password policy and I am using this Regex (default to my Identity Server) which accepts password as a combination of lower case, upper case, number and special character:

^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&*])).{0,100}$

I need to modify it so that it should not match string having more than 3 consecutive copies of the same character, as in e.g. Adminnnn@123.

Upvotes: 1

Views: 394

Answers (1)

flakes
flakes

Reputation: 23664

That was tricky, but I think this should work (try it out live here):

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&*])(?!.*(.)\1\1\1)[0-9a-zA-Z!@#$%&*]{0,100}$

I am using a 4 lookahead assertions and one negative lookahead assertion.

(?=.*[0-9])         must contain a number 
(?=.*[a-z])         must contain a lower case
(?=.*[A-Z])         must contain an upper case
(?=.*[!@#$%&*])     must contain a special character
(?!.*(.)\1\1\1)     must not repeat the character in group 1 more than 3 times
[0-9a-zA-Z!@#$%&*]  is composed of these characters
{0,100}             0 to 100 symbols allowed

Upvotes: 1

Related Questions