The same way you did to limit later:
"([0-9][0-9]?[0-9]?[0-9]?[0-9]?(\\.)?([0-9]?[0-9]?))"
That is, the first is mandatory, and the following 4 are optional. However, I have some suggestions to improve this regex:
Use the keys to choose the number of times an element will repeat itself. exp{n}
means that the expression needs to occur exactly n
times. exp{a,b}
means 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 complicates unnecessarily the regex:
"[0-9]{1,5}\\.?[0-9]{0,2}"
This way it is still possible to have a point without any digit on the front, or no point and two digits more. 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 interval [0-9]
:
"\\d{1,5}(\\.\\d{1,2})?"
If you want to avoid left zeros, separate the case from the 0
with the case of [1-9]
followed by 0 to 4 digits:
"(0|([1-9]\\d{0,4}))(\\.\\d{1,2})?"
Kind of?
\d{1,5}(\.\d{1,2})?
(1 to 5 digits, and optionally the dot followed by 1 or 2 digits) P.S. These groups are capture? Or whatever?– mgibsonbr