simbabque
simbabque

Reputation: 54373

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

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?

Upvotes: 5

Views: 1551

Answers (4)

burning_LEGION
burning_LEGION

Reputation: 13450

Use this regular expression

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

Upvotes: 3

Alex K.
Alex K.

Reputation: 175916

Alternation alternative:

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

Upvotes: 5

DoctorRuss
DoctorRuss

Reputation: 1439

Match 7 digits, then match an optional two digits.

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

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336418

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

Upvotes: 6

Related Questions