Home > Software engineering >  Regex for 0-2 including decimals up to two decimals it should include 0,1,2 the range from 0.00 to 2
Regex for 0-2 including decimals up to two decimals it should include 0,1,2 the range from 0.00 to 2

Time:12-14

I have tried so many regex for range from 0.00 to 2.00 with following

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

Its accepting 111 or 101 or 011 which are invalid.

CodePudding user response:

Try this:

^                         # - Anchor the match to start-of-text, followed by
(                         # - A group, consisting of alternatives. Either
  (                       #     - a group, itself consisting of
    2                     #         - the integer 2, followed by
    (\.00?)?              #         - an optional decimal fraction of zero (`.0` or `.00`)
  )                       #
|                         #     OR
  (                       #     - a group, itself consisting of
    [0-1]                 #         - the integers `0` or `1`, followed by
    (\.[0-9][0-9]?)?      #         - an optional decimal fraction of 1 or 2 digits
  )                       #
)                         # The whole of which is followed by
$                         # - end-of-text

Turned into a function,

const isBetweenZeroAndTwo = /^((2(\.00?)?)|([0-1](\.[0-9][0-9]?)?))$/.test ;

Which can be invoked as isBetweenZeroAndTwo( '1.23' ).

CodePudding user response:

I would complete Nicholas Carey's regex so that it also accepts following valid JS numbers (afaik), meeting the awaited range condition:
1.
.27
001.31
1.99

/^\ ?0*((2(\.0?0?)?)|((0?|1)(\.[0-9]?[0-9]?)?))$/

However, if your need is in JS (and not in a html pattern or similar), I would advise NOT using a regex.
Something like this would be much easier to understand and maintain:

function checkRange(value, min, max){
  return !isNaN(value) && value>=min && value<=max;
}
  • Related