Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex decimal values between 0 and 1 up to 4 decimal places

Tags:

I am writing a C# web application and verify data in a textbox using this regular expression that only accepts positive decimal values between 0 and 1:

^(0(\.\d+)?|1(\.0+)?)$

I would to adapt like the regex to restrict entries to 4 decimal places of precision.

Allowed

0
0.1
0.12
0.123
0.1234
1

Not allowed

-0.1
-1
1.1
2

I have found the following regex that only allows up to 4 decimal places, but I am unsure on how to combine the two.

^(?!0\d|$)\d*(\.\d{1,4})?$

Any help is greatly appreciated, thanks.

like image 310
Simon Avatar asked Jan 10 '17 18:01

Simon


1 Answers

You need to set replace the + quantifier with the limiting {1,4}:

^(0(\.[0-9]{1,4})?|1(\.0{1,4})?)$
           ^^^^^        ^^^^^ 

See the regex demo

Details:

  • ^ - start of string
  • ( - Outer group start
    • 0 - a zero
    • (\.[0-9]{1,4})? - an optional sequence of a . followed with 1 to 4 digits
    • | - or
    • 1 - a 1
    • (\.0{1,4})?) - an optional sequence of . followed with 1 to 4 zeros
  • $ - end of string.
like image 154
Wiktor Stribiżew Avatar answered Sep 22 '22 10:09

Wiktor Stribiżew