Reputation: 13
What is the regular expression for a decimal number with a maximum precision of 2 and decimal number should be in the range of 0-10 either positive or negative?
Valid Examples:
10.0
-9.5
-10
5
1.5
-0.5
0.5
8.25
Invalid Examples:
12.1232
2.23332
e666.76
11
-11
I have tried ^(?:10(?:\.0)?|[1-9](?:\.[0-9])?|0?\.[1-9])$
which basically checks positive decimal number in a range.
Also, tried ^\-?(\d+\.?\d*|\d*\.?\d+)$
which checks any decimal number.
I don't know how can I merge both regex.
Upvotes: 1
Views: 145
Reputation: 626851
You may use
^-?(?:\d(?:\.\d{1,2})?|10(?:\.0{1,2})?)$
See the regex demo and the regex graph:
Details
^
- start of string-?
- an optional -
symbol(?:
- start of a non-capturing group:
\d
- any digit(?:\.\d{1,2})?
- an optional sequence of a dot and 1 or 2 digits|
- or10
- 10
string(?:\.0{1,2})?
- an optional sequence of a .
and then 1 or 2 zeros)
- end of a non-capturing group$
- end of string.Upvotes: 3