-2

I'm trying:

\d{3}|\d{11}|\d{11}-\d{1}

to match three-digit numbers, eleven-digit numbers, eleven-digit followed by a hyphen, followed by one digit. But, it only matches three digit numbers!

I also tried \d{3}|\d{11}|\d{11}-\d{1} but doesn't work.

Any ideas?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
r.zarei
  • 1,261
  • 15
  • 35

4 Answers4

1

There are many ways of punctuating phone numbers. Why don't you remove everything but the digits and check the length?

Note that there are several ways of indicating "extension":

+1 212 555 1212 ext.35
egrunin
  • 24,650
  • 8
  • 50
  • 93
0

If the first part of an alternation matches, then the regex engine doesn't even try the second part.

Presuming you want to match only three-digit, 11 digit, or 11 digit hyphen 1 digit numbers, then you can use lookarounds to ensure that the preceding and following characters aren't digits.

(?<!\d)(\d{3}|\d{11}|\d{11}-\d{1})(?!\d)
Anon.
  • 58,739
  • 8
  • 81
  • 86
0

\d{7}+\d{4} will select an eleven digit number. I could not get \d{11} to actually work.

Cloudkiller
  • 1,616
  • 3
  • 18
  • 26
  • In addition to matching an eleven digit number, `\d{7}+\d{4}` will also match 18, 25, 32, 39 etc. digit numbers. – Anon. Feb 01 '11 at 22:04
0

This should work: /(?:^|(?<=\D))(\d{3}|\d{11}|\d{11}-\d{1})(?:$|(?=\D))/
or combined /(?:^|(?<!\d))(\d{3}|\d{11}(?:-\d{1})?)(?:$|(?![\d-]))/

expanded:

/ (?:^ | (?<!\d))       # either start of string or not a digit before us
  (                     # capture grp 1
      \d{3}                 # a 3 digit number
    |                     # or
      \d{11}                # a 11 digit number
      (?:-\d{1})?           # optional '-' pluss 1 digit number
  )                     # end capture grp 1
  (?:$ | (?![\d-]))     # either end of string or not a digit nor '-' after us
/