Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a regex quantifier that says "either x or y repeats"?

Tags:

regex

I want to match a string containing only numbers with either exactly 7 digits or exactly 9 digits.

/^\d{7}$|^\d{9}$/

Is there another way to write this, similar to /\d{7,8}/ for 7 or 8 digits?

like image 279
simbabque Avatar asked Dec 05 '22 15:12

simbabque


1 Answers

How about this:

/^\d{7}(?:\d{2})?$/

Explanation:

^      # Start of string
\d{7}  # Match 7 digits
(?:    # Try to match...
 \d{2} #  2 digits
)?     # ...optionally
$      # End of string
like image 119
Tim Pietzcker Avatar answered Feb 16 '23 11:02

Tim Pietzcker