password validation with regex in java

To require the characters to be in a special order is the weirdest password requirement I have ever heard and I can not believe that your customer really wants this.

Stated this I can explain your regex to you.

The lookahead assertions (the (?=...) stuff), you are using in your regex, are normally used, when the required characters can be in any order. If you really don’t have this requirement, then your regex is simple, you just need to skip your lookaheads.

This will match your requirements:

String pattern="[a-z]{2,}[A-Z]{2,}[0-9]{2,}[@#$%&]{2,}";

Just in case you want to allow all letters, digits and all other characters in your passwords, use Unicode code properties:

String pattern="p{Ll}{2,}p{Lu}{2,}\d{2,}[^\p{L}\d]{2,}";

Leave a Comment