Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex to match String password

Tags:

java

regex

I have recently encountered this question in the text book:

I am suppose to write a method to check if a string have:

  1. at least ten characters
  2. only letters and digits
  3. at least three digits

I am trying to solve it by Regx, rather than iterating through every character; this is what I got so far:

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

But this only matches the first two conditions. How should I go about the 3rd condition?

like image 964
Milk_QD Avatar asked Jan 27 '26 02:01

Milk_QD


1 Answers

You could use a positive lookahead for 3rd condition, like this:

^(?=(?:.*\d){3,})[a-z0-9]{10,}$
  • ^ indicates start of string.
  • (?= ... ) is the positive lookahead, which will search the whole string to match whatever is between (?= and ).
  • (?:.*\d){3,} matches at least 3 digits anywhere in the string.
    • .*\d matches a digit preceded by any (or none) character (if omitted then only consecutive digits would match).
    • {3,} matches three or more of .*\d.
    • (?: ... ) is a non-capturing group.
  • $ indicates end of string.
like image 193
Gerry Avatar answered Jan 29 '26 16:01

Gerry



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!