0

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?

DaveDev
  • 41,155
  • 72
  • 223
  • 385

2 Answers2

1
^(([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.

Simon
  • 7,182
  • 2
  • 26
  • 42
0

This should work:

^(|([1-9]){3,5}[1-8])$
Spontifixus
  • 6,570
  • 9
  • 45
  • 63
fejese
  • 4,601
  • 4
  • 29
  • 36