Search code examples
regexflex-lexerlexical-analysisdigit

how to make a regular expressions to accept only digits not started with zero or zero only?


I'm trying to create a regex to accept digits not starting with zero or a single zero digit.

Example matches

0
50
798

Example rejects

01
046
0014
00
0001

My attempt was to use /[0]|[1-9][0-9]*/ to match the values in the following text:

0, 50, 798
01, 046, 0014, 00, 0001

This attempt can be run at http://regexr.com/3bb00


Solution

  • Use following regex :

    ^(0|[1-9]\d*)$
    

    see Demo https://regex101.com/r/zT8uI2/2

    This regex contains 2 part, 0 or [1-9]\d* which is a digit that doesn't starts with zero.

    Note that if you want to match your numbers within other texts you need a word boundary instead of start and end anchors :

    \b(0|[1-9]\d*)\b
    

    see demo https://regex101.com/r/zT8uI2/3