Java – Regular expressions validate passwords that are accepted only between fixed lengths

Regular expressions validate passwords that are accepted only between fixed lengths… here is a solution to the problem.

Regular expressions validate passwords that are accepted only between fixed lengths

I have a regular expression to validate passwords and it only accepts passwords between 10 and 16.

However, it returns true even if I enter more than 16 characters.

My regular expression is:

^(?=.{ 10,16})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&+=]).*$

Solution

Use (?=.{ 10,16}) Forward, you set a minimum length, 10,,16 is not important because you did not add $ at the end to tell the match to stop matching after 16 characters.

You can add $ after {10,16},

or remove lookahead and add {10,16} $ before the final result.

I recommend following the following rule: the number of antecedents must be conditional minus 1 (see rexegg.com for reference:

).

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&+=]).{ 10,16}$
^^^^                                                ^^^^^^^^

See the regex demo .

Details

  • ^ – The beginning of the string
  • (?=.*[0-9]) – At least one digit
  • (?=.*[a-z]) – At least a lowercase ASCII letter
  • (?=.*[A-Z]) – At least one uppercase ASCII letter
  • (?=.*[!@#$%^&+=]) – At least one special character defined in the collection
  • .{ 10,16} – Any 10 to 16 characters
  • $ – End of string.

In Java, if you use a pattern in the .matches() method, you don’t need leading ^ and trailing $It requires a complete string match.

Java:

if (s.matches("(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&+=]).{ 10,16}")) {
    return true;
}

Related Problems and Solutions