-3

Is there a regex that allow if number start with 1 the length will be 10 and if number start other than 1 length is 9.

Examples:

  • 012345678 (since it starts with 0 the length required is 9)

  • 1234567890 (since it starts with 1 the length required is 10)

I try ^[1][0-9]{8,9} but it only do for the b condition.

I need a regex that will do both conditions.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
david
  • 9
  • 2

1 Answers1

4

The ^[1][0-9]{8,9} pattern only matches strings that start with 1 and then have 8 or 9 digits, but can end with any text after these patterns.

You may use

^(?:1[0-9]{9}|[02-9][0-9]{8})$

See the regex demo

Details

  • ^ - start of string
  • (?: - start of a non-capturing group:
    • 1 - 1 digit
    • [0-9]{9} - any nine ASCII digits
  • | - or
    • [02-9] - any ASCII digit other than 1
    • [0-9]{8} - any eight ASCII digits
  • ) - end of the group
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563