The same way you did to limit it later:
"([0-9][0-9]?[0-9]?[0-9]?[0-9]?(\.)?([0-9]?[0-9]?))"
That is, the former is required, and the following 4 are optional. However, I have some suggestions for improving this regex:
Use the keys to choose the number of times an element will repeat itself. exp{n}
means that the expression must occur exactly n
times. exp{a,b}
means that it needs to occur at least a
and at most b
times:
"([0-9]{1,5}(\.)?([0-9]{0,2}))"
If these groups are not capture, I suggest removing them, as this unnecessarily complicates regex:
"[0-9]{1,5}\.?[0-9]{0,2}"
This is still possible to have a point with no digits in front, or no point and two digits too long. Connect the dot to the digits, and require at least 1 digit if the dot is present:
"[0-9]{1,5}(\.[0-9]{1,2})?"
You can use \d
(escaped, \d
) to represent a digit instead of the [0-9]
range:
"\d{1,5}(\.\d{1,2})?"
If you want to avoid zeros on the left, separate the case from 0
with the case of [1-9]
followed by 0 to 4 digits:
"(0|([1-9]\d{0,4}))(\.\d{1,2})?"