Java Regex matches String password

I recently came across this question in a tutorial:

I have to write a method to check if the line is there:

  • at least ten characters
  • only letters and numbers
  • at least three digits

I am trying to solve it with Regx rather than iterating through each character; this is what i got so far:

String regx = "[a-z0-9]{10,}";

      

But this only meets the first two conditions. How do I go to the 3rd condition?

+3


source to share


1 answer


You can use a positive outlook for the 3rd condition, for example:

^(?=(?:.*\d){3,})[a-z0-9]{10,}$

      



  • ^

    indicates the beginning of a line.
  • (?= ... )

    is a positive lookahead that will search the entire string according to what is between (?=

    and )

    .
  • (?:.*\d){3,}

    matches at least 3 digits anywhere in the string.
    • .*\d

      matches the value preceded by a character (or none) (if omitted, then only consecutive digits will match).
    • {3,}

      matches three or more .*\d

      .
    • (?: ... )

      - non-exciting group.
  • $

    indicates the end of the line.
+4


source







All Articles