Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expressions match exactly 7 or 9 digits [duplicate]

Tags:

regex

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

like image 832
Oliver Millington Avatar asked Aug 03 '12 14:08

Oliver Millington


People also ask

How do you match a regular expression with digits?

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.

Which regex matches one or more digits?

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.

What does ?= Mean in regex?

?= 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).

What would the following mean in a regular expression a z0 9?

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.


2 Answers

/^\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.

like image 98
chaos Avatar answered Oct 15 '22 07:10

chaos


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})$/
like image 27
Bergi Avatar answered Oct 15 '22 07:10

Bergi