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.
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|
- or1
- a 1
(\.0{1,4})?)
- an optional sequence of .
followed with 1 to 4 zeros$
- end of string.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