Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains a particular digit only (e.g. "111")

Tags:

java

string

regex

Need to find out if a given string contains just a particular digit only - e.g. "111", "2", "33" should return true.

"12" should return false.

Empty string ("") should also return true.

The string contains only digits and no other characters.

Wrote an ugly Java regex that seems to work, but can't help but think it should be written in a much shorter manner:

str.matches("1*|2*|3*|4*|5*|6*|7*|8*|9*|0*")

Is there a simpler and more elegant way to do the above, avoiding the listing of all digits one by one?

like image 918
Rnam Avatar asked Jan 27 '23 08:01

Rnam


1 Answers

You can use this regex, which uses group to capture the first digit and then uses back-reference to ensure that the following digits all are same,

^(\d)?\1*$

Explanation:

  • ^ - Start of string
  • (\d)? - Matches one digit and captures in group1 and ? makes it optional to allow matching empty strings.
  • \1* - Matches the same digit zero or more times
  • $ - End of string

Regex Demo

Java code,

List<String> list = Arrays.asList("5","5555","11111","22222","1234", "");
list.forEach(x -> {
    System.out.println(x + " --> " + x.matches("(\\d)?\\1*"));
});

Prints,

5 --> true
5555 --> true
11111 --> true
22222 --> true
1234 --> false
 --> true
like image 150
Pushpesh Kumar Rajwanshi Avatar answered Jan 30 '23 04:01

Pushpesh Kumar Rajwanshi