Jack
Jack

Reputation: 497

Using regex to check if a string has at least two numbers

After digging around on stack overflow, I found some code which checks if the string is alphanumeric and longer that 8 chars. It works great. Now how do I make it return true if it contains at least 2 numbers? I think I have to add \d{2} somewhere.

String pattern = "^[a-zA-Z0-9]*$";

if (s.matches(pattern) && s.length() >= 8){
    return true;
}
return false;

Upvotes: 4

Views: 14385

Answers (3)

Bohemian
Bohemian

Reputation: 424993

You can do it in one line:

return s.matches("(?=(.*?\\d){2})[a-zA-Z0-9]{8,}");

Upvotes: 3

Unihedron
Unihedron

Reputation: 11041

Assert with a positive lookahead:

^(?=(?:\D*\d){2})[a-zA-Z0-9]*$

Here is a regex demo.

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174696

You don't need a separate if condition. A single regex will do all for you.

String pattern = "^(?=.*?\\d.*\\d)[a-zA-Z0-9]{8,}$";

Upvotes: 6

Related Questions