1

Want to find whether my string contains every digit from 0 to 9 or not. I am currently using following logic :

if (str.contains("0") && str.contains("1") && str.contains("2") && str.contains("3") && str.contains("4") && str.contains("5") && str.contains("6") && str.contains("7") && str.contains("8") && str.contains("9"))
{
    return true;
}

I believe this will not be very optimized if string is too big. How can I use a pattern and find using String.matches whether it has all numbers or not through regex ?

This is not a duplicate of most other regex questions in the forum wherein 'OR' related char patterns are discussed, here we're talking about 'AND'. I need whether a string contains each of the given characters (i.e. digits) or not. Hope it clarifies.

Thanks, Rajiv

Rajiv
  • 45
  • 9

1 Answers1

1

I would not recommend a regex for this task as it won't look elegant. It will look like (hover mouse over to see the spoiler):

str.matches("(?s)(?=[^1]*1)(?=[^2]*2)(?=[^3]*3)(?=[^4]*4)(?=[^5]*5)(?=[^6]*6)(?=[^7]*7)(?=[^8]*8)(?=[^9]*9)(?=[^0]*0).*")

Instead, in Java 8, you can use

bool result = s.chars().filter(i -> i >= '0' && i <= '9').distinct().count() == 10;

It filters all the string characters (s.chars()) that are digits (.filter(i -> i >= '0' && i <= '9')), only keeps unique occurrences (with .distinct()), and then checks their count with .count(). If the count is equal to 10, there are all ten ASCII digits.

So, the following code:

String s = "1-234-56s78===90";
System.out.println(s.chars().filter(i -> i >= '0' && i <= '9').distinct().count() == 10);

prints true.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563