Rnam
Rnam

Reputation: 65

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

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?

Upvotes: 4

Views: 348

Answers (1)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

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

Upvotes: 8

Related Questions