Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression validator accept number with decimal numbers 0 or 5 in range 0-5

Tags:

regex

I'm trying to write a Regular Expression validator to accept numbers only with decimal part 0 or 5 only and in range 0-5 . for example:

-1          false
-.5         false
-0          false

000000      true
0.0         true
0000.       true
0           true
.50000000   true
00001.      true
01.50       true
2.00000     true
2.5000      true
03          true
03.5        true
0004        true
0004.5000   true
00005.0     true

0           true
0.5         true
1           true
1.5         true
2           true
2.5         true
3           true
3.5         true
4           true
4.5         true
5           true

1.05        false
5.5         false
10          false
20          false
30          false
40          false
50          false

No matter how many 0 in front or behind the numbers it can be valid.

I tried this one ^[0-5]+(?:\.[05]0?)?$ but it fails on cases: 0000., .5, 001. and 5.5

Many thanks!

like image 406
Chris So Avatar asked Dec 19 '22 14:12

Chris So


2 Answers

You can use

^0*(?:[0-4]?(?:\.5?0*)?|5(?:\.0*)?)$

Explanation:

^0*                  # allow leading 0s
    (?:              # non capturing group
        [0-4]?       # below 5: number starts with 0-4
        (?:\.5?0*)?  # optional: decimal dot, might be followed by one 5 and 0s.
    |                # or
        5(?:\.0*)?   # 5, possibly followed by 0s
    )
$

Be aware this also validates an empty string or a single .. Tell me if that's an issue, as a quickfix you can add looks ahead at the beginning to check the length and content: (?=.)(?!\.$).

See demo here.

like image 184
Robin Avatar answered Jan 31 '23 08:01

Robin


You can use the following:

^0*5(?:\.0*)?$|^0*[1-4]?(?:\.[05]?0*)?$

Regular expression visualization

Demo

like image 33
Ulugbek Umirov Avatar answered Jan 31 '23 09:01

Ulugbek Umirov