3

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?

2
  • Possible duplicate of Password matching with regex Commented Jul 24, 2017 at 0:48
  • Thank you so much, should have searched before asking >< Commented Jul 24, 2017 at 5:10

1 Answer 1

4

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.
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much for your detailed explanation first. I am still a bit lost about the positive lookahead and ?: as this is my first time encountering them. My current understanding of them is the positive lookahead to allow (?:.*\d){3,} to search the whole string. and the ?: allows the .*\d{3} to match any three digits but not remembering them, so it does not contribute to the final {10,}
And this form of Regx can only be used with class Pattern in Java? Not with String class methods such as .matches() and .replaceAll()
@Anlinyang Yes, you got the lookahead right, and the ?: allows to use parenthesis to group an expression (e.g. .*\d) without capturing it (you need to group ithe expresssion in order to apply {3,} on it). You could use the same expression without the ?: and it will still work.
@Anlinyang I'm not sure, i'm not Java savvy, but s far as i understand String class methods accept simple regex, so i guess you will need to create a pattern first and match the string agsinst it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.