Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex to check is string has at least two numbers

Tags:

java

regex

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;
like image 664
Jack Avatar asked Dec 19 '22 10:12

Jack


1 Answers

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,}$";
like image 101
Avinash Raj Avatar answered Jan 06 '23 04:01

Avinash Raj