Reputation: 47
I'm trying to write regular expressions for the following numeric ranges however need some assistance to write them correctly.
All numeric values to match against are to 1 decimal place.
I believe I've manage to correctly get the correct Regular expression for the 0.0 to 59.9 range however am having difficulty with the others.
^[1-5]?([1-9](?:\.[0-9])?|0?\.[1-9])$
Upvotes: 0
Views: 339
Reputation: 1317
check this:
// 0.0 to 59.9
^[012345]?[0-9]\.[0-9]$
//60.0 to 119.9
^(?:[6789]|10|11)[0-9]\.[0-9]$
//120.0 to 239.9
^(?:1[0-9]{2}|2[0123][0-9])\.[0-9]$
//240.0 to 419.9
^(?:2[456789][0-9]|3[0-9]{2}|4[01][0-9])\.[0-9]$
//1200.0 to 1799.9
^(?:1[234567])[0-9]{2}\.[0-9]$
//Anything greater than 3600.0
^(?:36[0-9]{2}|3[789][0-9]{2}|[456789][0-9]{3}|[0-9]{5}[0-9]*)\.[0-9]$
Upvotes: 2
Reputation: 758
You're using the wrong tool for the job. While you could use a regex to do what you're trying to do, it's not well suited to do it well let alone efficiently. A simple if
, else if
, and else
construct will suit you the best. If you want to ignore anything after the first decimal place when doing the check, you can use .toFixed(1)
and then convert it back to a float using parseFloat(string)
. You could also use Math.round(float)
depending on how you want to treat numbers with more than one decimal place.
Note: The specific functions given are JavaScript examples, depending on your language they may be slightly different.
Upvotes: 0