Shubham KUMAR
Shubham KUMAR

Reputation: 13

Regular Expression for any positive or negative decimal number in a range of 0 to 10

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

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626851

You may use

^-?(?:\d(?:\.\d{1,2})?|10(?:\.0{1,2})?)$

See the regex demo and the regex graph:

enter image description here

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
    • | - or
    • 10 - 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

Related Questions