Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for complex password

Tags:

java

regex

I need to validate passwords that needs to fulfill the following rules:

  • Minimum length is 8 characters
  • All characters need to be unique
  • At least one of the characters is capitalized
  • At least one character is a non-alphabetic character, a digit or a hyphen
  • Non-alphabetic characters should not be placed as the first two or last two characters

I can't figure out how to validate this using regular expressions. Can anybody help me?

like image 737
mmjmanders Avatar asked Feb 23 '26 00:02

mmjmanders


1 Answers

^(?=.*[A-Z])(?=.*(?:\d|-))(?!.*(.).*\1)[a-zA-Z]{2}.{4,}[a-zA-Z]{2}$

Try this.See demo.

https://regex101.com/r/eZ0yP4/12

As you can see step by step all conditions are met with the help of lookahead.

(?=.*[A-Z])===at least one Capital

(?=.*(?:\d|-))===at least one digit or -

(?!.*(.).*\1)=== no duplicates

[a-zA-Z]{2}.{4,}[a-zA-Z]{2}===alphabetic characters as first two and last two.

like image 61
vks Avatar answered Feb 25 '26 15:02

vks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!