1

I have the following regex which validates that a string contains only numbers and is between 10 and 11 characters in length.

^[0-9]{10,11}$

However, if the string has a length of 11, I need to validate that the first character is a 1. If the length of the string is 10, no further validation is necessary.

examples of valid strings

3455558899

15554445555

example of an invalid string

25554445555

85554445555

Is this possible with regex? BTW, this regex will be used in a Java application.

0

2 Answers 2

2

You may use this regex with an optional match of 1 at start and then match next 10 digits:

^1?\d{10}$

RegEx Demo

This will make this regex match 11 digits when first digit is 1 or it will match 10 digits.

RegEx Details:

  • ^: Start
  • 1?: Optionally match 1 at start
  • \d{10}: Match exact 10 digits
  • $: End

In Java use following String to construct your regex:

String re = "^1?\\d{10}$";
Sign up to request clarification or add additional context in comments.

1 Comment

That works beautifully! Thanks, I really appreciate it!
1

If this is a numeric value, it's easier to convert to Long and then compare the value instead of regex.

String x = {your value};
Long i = Long.valueOf(x);
if(i <= 19999999999L) return true;

1 Comment

Interesting solution

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.