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.
CodePudding user response:
There are a few issues in the pattern:
- This part
[1-9][0-9]{0,4}
can match 1-5 digits as the quantifier is 0-4 times so it can match 10000 as well - You don't need
9999|9999.99
as those can already be matched by1-9][0-9]{0,4}
- This part
.d
matches any char except a newline followed by ad
char. You have to escape both to match a dot literally and a single digit - With those changes, you can omit the outer capture group
The 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 string
CodePudding user response:
Try this regex:
^0*(?!\.\d )[1-9]\d{0,3}(?:\.\d{1,2})?$
Explanation:
^
- matches start of the string0*
- matches 0 occurrences of digit0
(?!\.\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 string
CodePudding user response:
Another 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.