I’m working on a regex to match valid integer numbers such as the following:
- 0
- 1
- 99
- 999
However it should not allow matching an empty string. The closest I can get is:
(0)|\\d{1,3}
Which to me says a matching string will have either a zero or a series of digits between 1 and 3 characters long. However, empty strings still appear to match this pattern. What’s the proper way to exclude empty strings from this regex?
This will match (only) a series of one to three numeric digits (including 0 or 00 or 01 or 012 – not clear if those latter ones are desired):
It will not match empty string (but then neither will your original convoluted expression).
(To allow this as part of a bigger string, remove the
^and$anchors.)But perhaps regex is not best option here – does whatever base language you’re using not have an isNumeric function?
To allow 0 but not other 0-prefixed numbers, you can use:
Or, to ensure that’s the entire match: