remove leading zeros (optional) from regex, with max length

Viewed 32

I have a validation regex, that checks that the user sent a query param in this format- an integer with max length of 10 - meaning it can be an integer between 0 and 10, and it can also contain leading zeros (any number of zeros at the beginning), but its optional.

Examples:

String Result
12345 valid
000001234567890 valid
012345678900 not valid
12345678901 not valid
000000000012547 valid

this is my regex, but it doesn't seem to work

"^(0+)?|[0-9]{0,10}+$"

^(0+)? - this is suppose to be the optional leading zeros at the beginning

[0-9]{0,10}+ - this is suppose to be the integer with the length validation

1 Answers

You can use

^0*[1-9]\d{0,9}$
^0*[1-9][0-9]{0,9}$

See the regex demo. Details:

  • ^ - start of string
  • 0* - zero or more leading zeros
  • [1-9] - a non-zero digit
  • [0-9]{0,9} - zero to nine digits
  • $ - end of string.

If you allow an empty string, you can use

^(?:0*[1-9][0-9]{0,9})?$

where the pattern between anchors is optional.

Related