1

I am creating a validator for inputs on one of my text fields in java. The length of the input field should be 10 and the values should be any number in between 1-9. The catch is, the input should use the same character only 10x... So valid values should be such as the following:

1111111111
2222222222
....
9999999999

But if the entered text is something like 111111112, this should be considered as invalid entry.

Currently I use String.matches("^[0-9]+$") to check if the inputted values are valid but this still accepts 111111112 as valid. What is the correct approach to check if all 10 characters of the string is the same?

1 Answer 1

5

You can do it using back referencing:

String.matches("^([0-9])\1{9}$")

or:

String.matches("^([0-9])\\1{9}$")

DEMO

This only matches exactly 10 digits in a line that are all the same.

Sign up to request clarification or add additional context in comments.

3 Comments

That was fast, sshashank! +1 :)
@zx81, Thank you. :). We meet again
Now you made me laugh... Thanks for that. :) Catch you later, starting to watch a show.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.