My reg ex skills are almost zero and I am trying to match a field to have exactly 7 or 9 numbers (not between 7 or 9 so no 8 numbers is not valid).
I have tried (don't laugh)
/^([0-9]{7} | [0-9]{9})
and
/^([0-9]{7 | 9})
if someone could help and explain the answer that would be much appreciated.
I assume (maybe incorrectly) that is does not matter what (programming) language I am using
Thanks
To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.
Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits.
?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).
In a regular expression, if you have [a-z] then it matches any lowercase letter. [0-9] matches any digit. So if you have [a-z0-9], then it matches any lowercase letter or digit.
/^\d{7}(?:\d{2})?$/
\d
is modern regex shorthand for [0-9]
, using (?:
prevents a group capture you don't want or need from happening.
Your first approach works. Just leave out the blanks, add a $
to match the string end and the trailing slash delimiter. You also could replace [0-9]
with the shortcut \d
:
/^(\d{7}|\d{9})$/
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