Regular expression for password (at least 2 digits and one special character and minimum length 8)

I have been searching for regular expression which accepts at least two digits and one special character and minimum password length is 8. So far I have done the following: [0-9a-zA-Z!@#$%0-9]*[!@#$%0-9]+[0-9a-zA-Z!@#$%0-9]*


Something like this should do the trick.

^(?=(.*\d){2})(?=.*[a-zA-Z])(?=.*[!@#$%])[0-9a-zA-Z!@#$%]{8,}

(?=(.*\d){2}) - uses lookahead (?=) and says the password must contain at least 2 digits

(?=.*[a-zA-Z]) - uses lookahead and says the password must contain an alpha

(?=.*[!@#$%]) - uses lookahead and says the password must contain 1 or more special characters which are defined

[0-9a-zA-Z!@#$%] - dictates the allowed characters

{8,} - says the password must be at least 8 characters long

It might need a little tweaking e.g. specifying exactly which special characters you need but it should do the trick.


There is no reason, whatsoever, to implement all rules in a single regex. Consider doing it like thus:

Pattern[] pwdrules = new Pattern[] {
    Pattern.compile("........"),   // at least 8 chars
    Pattern.compile("\d.*\d"),     // 2 digits
    Pattern.compile("[-!"§$%&/()=?+*~#'_:.,;]") // 1 special char
  }

String password = ......;
boolean passed = true;

for (Pattern p : pwdrules) {
    Matcher m = p.matcher(password);
    if (m.find()) continue;
    System.err.println("Rule " + p + " violated.");
    passed = false;
}

if (passed) { .. ok case.. }
else { .. not ok case ... }

This has the added benefit that passwort rules can be added, removed or changed without effort. They can even reside in some ressource file.

In addition, it is just more readable.


Try this one:

^(?=.*\d{2,})(?=.*[$-/:-?{-~!"^_`\[\]]{1,})(?=.*\w).{8,}$

Here's how it works shortly:

  • (?=.*\d{2,}) this part saying except at least 2 digits
  • (?=.*[$-/:-?{-~!"^_[]]{1,})` these are special characters, at least 1
  • (?=.*\w) and rest are any letters (equals to [A-Za-z0-9_])
  • .{8,}$ this one says at least 8 characters including all previous rules. Below is map for current regexp (made with help of Regexper) Regexp mapUPD

Regexp should look like this ^(?=(.*\d){2,})(?=.*[$-\/:-?{-~!"^_'\[\]]{1,})(?=.*\w).{8,}$ Check out comments for more details.


Try this regex. It uses lookahead to verified there is a least two digits and one of the special character listed by you.

^(?=.*?[0-9].*?[0-9])(?=.*[!@#$%])[0-9a-zA-Z!@#$%0-9]{8,}$ 

EXPLANATION

^ #Match start of line.

(?=.*?[0-9].*?[0-9]) #Look ahead and see if you can find at least two digits. Expression will fail if not.

(?=.*[!@#$%]) #Look ahead and see if you can find at least one of the character in bracket []. Expression will fail if not.

[0-9a-zA-Z!@#$%0-9]{8,} #Match at least 8 of the characters inside bracket [] to be successful.

$ # Match end of line.