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
  • 38,095
  • 68
  • 199
  • 359

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
  • 6,782
  • 2
  • 23
  • 42
0

This should work:

^(|([1-9]){3,5}[1-8])$
Spontifixus
  • 6,133
  • 8
  • 38
  • 57
fejese
  • 4,353
  • 4
  • 25
  • 35