I need a regular expression that accept only integers or decimals from 1 to 9999.99. I tried this
^(?:[1-9][0-9]{0,4}(?:.d{1,2})?|9999|9999.99)$
but it is also accepting 10000.
I need a regular expression that accept only integers or decimals from 1 to 9999.99. I tried this
^(?:[1-9][0-9]{0,4}(?:.d{1,2})?|9999|9999.99)$
but it is also accepting 10000.
There are a few issues in the pattern:
[1-9][0-9]{0,4} can match 1-5 digits as the quantifier is 0-4 times so it can match 10000 as well9999|9999.99 as those can already be matched by 1-9][0-9]{0,4}.d matches any char except a newline followed by a d char. You have to escape both to match a dot literally and a single digitThe updated pattern looks like:
^[1-9]\d{0,3}(?:\.\d{1,2})?$
^ Start of string[1-9]\d{0,3} Match a single digit 1-9 and repeat 0 to 3 times a digit 0-9(?:\.\d{1,2})? Optionally match a . and 1 or 2 digits$ End of stringTry this regex:
^0*(?!\.\d+)[1-9]\d{0,3}(?:\.\d{1,2})?$
Explanation:
^ - matches start of the string0* - matches 0+ occurrences of digit 0(?!\.\d+) - zero-length match if the current position is not followed by a . and 1+ digits[1-9] - matches a digit from 1 to 9\d{0,3} - matches at-least 0 or at-most 3 occurences of a digit(?:\.\d{1,2})? - matches the decimal . followed by 1 or 2 digits. A ? at the end to make the fractional part optional$ - matches the end of stringAnother idea but there is not much difference regarding performance (just for fun).
^(?!0)\d{1,4}(?:\.\d\d?)?$
The looakhead (?!0) prevents starting with zero, so we can further match \d{1,4}.
Does not respect leading zeros. See this demo at regex101.