Search code examples
angularregex

How to write a regex for a decimal number scenario with a specific range?


I am trying to write a Regex that satisfies the below criteria. I tried below one though few of my criteria doesnt match with the below regex.

^([0-9]{1,2})(\.0)|(\.[1-9]{1,2})$
  1. A decimal number that is of nn.mm (nn,mm can be numbers [0-9])
  2. If mm is present for example if 01,02,03..09, then the second is not allowed, because first number is 0.

Valid values are `10.00, 10.10,99.12, 12.99, 10.11, 01.10, 00.00, 00.10, 1.1, 0.9, 0.1, 2.3, 1.10, 9.20, 4.56 ....

Invalid values are 00.01, 99.01, 12.09, 10.08, 10.01, 10.02...10.09 (because after decimal point, first digit is 0 which is invalid)

TO be more precise:

[0-9][0-9].0  //valid
[0-9][0-9].[0-9]0  //valid
[0-9].0  //valid
[0-9].[0-9]0  //valid
[0-9][0-9].[0-9]0 //valid

[0-9].0[0-9] //invalid
[0-9][0-9].0[0-9] //invalid

Solution

  • This regex should give you the results you want:

    ^[0-9]{1,2}\.(?:00?|[1-9][0-9]?)$
    

    It matches:

    • ^ : beginning of string
    • [0-9]{1,2} : 1 or 2 digits
    • \. : a period (.)
    • (?:00?|[1-9][0-9]?) : either:
      • 00? : a zero, followed by an optional 0; or
      • [1-9][0-9]? : a digit in the range 1-9, followed by an optional second digit
    • $ : end of string

    Regex demo on regex101