Reputation: 54373
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
Reputation: 1439
Match 7 digits, then match an optional two digits.
/^\d{7}(\d{2})?/
Upvotes: 2
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