quique
quique

Reputation: 129

Regex to allow number greater than 0.5

Hi i'm working on some regex now and i want to add the conditional to allow only numbers greater than 0.5 here is my regex

^(?![.0]*$)[0-9]+(?:\.[1-9]{1,2})?$

i just want to values between 0 and 0.5 don't match this. Thanks

Upvotes: 0

Views: 2335

Answers (5)

Charkan
Charkan

Reputation: 831

This regexp may works: (Check here)

^([0-9]+|[0-9]+[0-9]\.[0-9]+|[1-9]\.[0-9]+|0\.[5-9][0-9]*)$

Upvotes: 0

Toto
Toto

Reputation: 91385

You really should use @dontangg 's answer.

But if you want a regex, here is one that do the job:

^(?:0\.5[1-9]\d*|0\.[6-9]\d*|\d+[1-9](?:\.\d+)?)$

Explanation:

^                   : begining of string
    (?:             : begining of non-capture group
        0\.5[1-9]\d*:  0. followed by number greater than 50
        |           :
        0\.[6-9]\d* : 0. followed by number greater than 5 then any number of digits
        |           : OR
        \d+[1-9]    : any digit followed by number from 1 to 9
        (?:         : begining of non-capture group
            \.\d+   : a dot followed by any digits
        )?          : end of non capture group, optional
    )               : end of non-capture group
$                   : end of string

It matches:

0.51
12
12.34

It doesn't match:

0
0.2
0.25
0.5
0.50

Upvotes: 0

quique
quique

Reputation: 129

This regex works allows two decimals and numbers greater than 0.50

^((?!0*(\.0+)?$)[0-9]+|[0-9]+[0-9]\.[0-9]{1,2}+|[1-9]\.[0-9]+|0\.[5-9][0-9]?)$

Upvotes: 0

chiliNUT
chiliNUT

Reputation: 19573

(^(?![.0]*$)[1-9]+(?:\.[0-9]{1,2})?$)|(^(?![.0]*$)[0]+(?:\.[5-9][0-9]*)?$)

and its easy to read too!

Upvotes: 1

dontangg
dontangg

Reputation: 4809

Regular expressions are awesome, but they can get hard to read and maintain. This feels like a scenario where you should just parse the string and compare the value.

var num = parseFloat(input);
if (num > 0.5)
    ...

Upvotes: 8

Related Questions