Reputation: 85
I want to validate that a number with three optional integer and four digits mandatory after the decimal point is greater than 1. For example:
0.0000 [No]
0.9999 [No]
1.0000 [No]
1.0009 [Yes]
01.0000 [No]
01.0009 [Yes]
001.0000 [No]
011.0000 [Yes]
222.0000 [Yes]
000.9999 [No]
I have been created this regex:
(?!^1*$)(?!^1*\.0*$)^(?:[1-9]|\d\d\d)(?:\.\d{4,4})$
But it doesn't work for all the cases
Upvotes: 3
Views: 566
Reputation: 75840
Looks like you can use:
^(?!0*\.|0*1\.0*$)\d{1,3}\.\d{4}$
See the demo
^
- Start string anchor.(?!
- Open negative lookahead:
0*\.
- Prevent 0+ leading zero's upto a literal dot;|
- Or:0*1\.0*$
- Prevent 0+ leading zero's up to a 1 followed by a literal dot and trailing zero's until string ends.)
- Close negative lookahead.\d{1,3}\.\d{4}
- 1-3 Leading digits, a literal dot and 4 trailing digits.$
- End string anchor.Upvotes: 2
Reputation: 163217
If supported, you might use a negative lookahead to exclude some of the possible matches:
^(?!0*1\.0+$|\d{4}\.)0*[1-9]\d*\.\d{4}$
The pattern matches
^
Start of string(?!
Negative lookahead, not directly to the right
0*1\.0+$
Match optional zeroes, a dot and 1 or more zeroes|
or\d{4}\.
Match 4 digits and a dot)
Close lookahead0*[1-9]\d*
Match optional zeroes, a digit 1-9 and optional digits\.\d{4}
match a . and 4 digits$
End of stringUpvotes: 4
Reputation: 784998
You may use this regex to allow up to 3 digits before .
and 4 digits after .
to match values greater than 1
only:
^(?!0*1\.0+$)(?=0*[1-9])\d{1,3}\.\d{4}$
RegEx Details:
^
: Start(?!0*1\.0+$)
: Positive Lookahead condition to assert that we don't have a case of optional zeroes followed by 1.0000
(?=0*[1-9])
: Positive Lookahead condition to assert that we have at least on non-zero digit ahead\d{1,3}
: Match 1 to 3 digits\.
: Match a .
\d{4}
: Match 4 digits$
: EndUpvotes: 6