Reputation: 42185
I have the following regex:
^([1-9]){3,5}[1-8]$
it works to restrict strings within a certain range, but now I need to change that so that it'll also allow an empty string. How can I do this?
Upvotes: 0
Views: 23
Reputation: 7250
^(([1-9]){3,5}[1-8])?$
Use (?:
if you care about the captured groups, if you don't, you can remove the brackets around [1-9]
. Brackets around the whole sequence must be kept, though, so the ?
quantifier still applies correctly (preceding group zero or one times). So the slightly shorter (maybe more correct) version would be:
^(?:\d{3,5}[1-8])?$
This will return exactly one match, which is the input string as a whole.
Upvotes: 1