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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With