The regex control accepts a number with decimal numbers 0 or 5 in the range 0-5

I am trying to write a regex validator to accept numbers with only the decimal part 0 or 5 and only in the range 0-5. eg:

-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 0s are in front or behind the digits, it can really be.

I tried this ^[0-5]+(?:\.[05]0?)?$, but it fails in the following cases: 0000., .5, 001.and5.5

Many thanks!

+4
source share
4 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
    )
$

Remember that this also checks for an empty string or single .. Tell me if this is a problem, as a quick fix, you can add in the beginning to check the length and contents (?=.)(?!\.$).

.

+5

:

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

Regular expression visualization

+2

This should do the trick:

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

http://rubular.com/r/bDM7mOHL54

+1
source

Here is another one:

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

enter image description here

+1
source

Source: https://habr.com/ru/post/1542630/


All Articles