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!
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.
You can use the following:
^0*5(?:\.0*)?$|^0*[1-4]?(?:\.[05]?0*)?$
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With