decimal and integer numbers that is less 91 with regex

Viewed 72

I have this regex /^(0|[1-9]\d*)(\.\d+)?$/

It allow all decimal and integer numbers.

What I need it to add all numbers that is less than 91.

How could I implement that ?

Please help

3 Answers

Integers or decimals less than 91 could be achieved like so:

^(?:0|[1-8]\d?|90?)(?:\.\d+)?$

See an online demo.

  • ^ - Start line anchor.
  • (?: - Open 1st non-capture group:
    • 0|[1-8]\d?|90? - Match zero or 1-8 and an optional digit or a nine with an optional zero.
    • ) - Close 1st non-capture group.
  • (?: - Open 2nd non-capture group:
    • \.\d+ - A literal dot and 1+ digits.
    • )? - Close 2nd non-capture group and make it optional.
  • $ - End line anchor.

Edit: If you don't mind matching a double zero as per "00" or "00.0000" you could use:

^(?:\d0?|[1-8]\d?)(?:\.\d+)?$

Or, even less verbose, using a negative lookahead:

^(?!9[1-9])\d\d?(?:\.\d+)?$

With your shown samples, please try following.

^(?:[0-9]|[0-8][0-9]|90)(?:\.\d+)?$

Online demo for above regex

OR could be shorten as following too:

^(?:[0-8]?[0-9]|90)(?:\.\d+)?$

Explanation: Adding detailed explanation for above.

^(?:                   ##Matching from starting of value and starting a non-capturing group here.
 [0-9]|[0-8][0-9]|90   ##Matching either 0 to 9 OR till 89 OR 9 here.
)                      ##Closing non-capturing group here.
(?:\.\d+)?$            ##In a non-capturing group matching dot followed by 1 or more digits keep it optional at the last of value.


Bonus solution: Based on my assumption only, in case you want to match additional zeroes but still lesser than 91 then try following.

^(?:0+)?(?:[0-9]|[0-8][0-9]|90)(?:\.\d+)?$

What about this?

^(90|[0-8][0-9])$

Simply match 90 or 00 until 89.

Related