DaveDev
DaveDev

Reputation: 42185

How can I modify this regex to require a specific numeric range and also allow an empty string?

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

Answers (2)

fejese
fejese

Reputation: 4628

This should work:

^(|([1-9]){3,5}[1-8])$

Upvotes: 0

Seimen
Seimen

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

Related Questions