0

Possible Duplicate:
A comprehensive regex for phone number validation

I've got this.

1?\s*-?\s*(\d{3}|\(\s*\d{3}\s*\))\s*-?\s*\d{3}\s*-?\s*\d{4}

It is matching a lot of the phone numbers, but it's not catching these two:

(123) 456-7890 or 123.456.7890

Community
  • 1
  • 1
Hell.Bent
  • 1,667
  • 9
  • 38
  • 73

3 Answers3

0

Awhile back I asked a question about a regex for a certain number of digits in a string. The answer gave me this regex (\D*\d){10}{n}.

I've actually used this for phone number validation since then. I do not care what format they give me a phone number in, as long as it contains 10 digits. If all you care about is that you get the area code + phone number, then this may work for you as well.

Community
  • 1
  • 1
Brandon
  • 68,708
  • 30
  • 194
  • 223
0

This is a simplified version of your original regex that should do what you are asking for.

1?[\s-(.]*?\d{3}[ -).]*?\d{3}[ -.]*?\d{4}
Ryan Pedersen
  • 3,177
  • 27
  • 39
0

A couple of monsters
Capture groups 1,2,3 hold the parts of the phone number. This is a bare bones validation.
Anything more and it gets like godzilla.

Area code not required
/^(?:\s*(?:1(?=(?:.*\d.*){10}$)\s*[.-]?\s*)?(?:\(?\s*(\d{3}|)\s*\)?\s*[.-]?))\s*(\d{3})\s*[.-]?\s*(\d{4})$/

Area code required
/^(?:\s*(?:1(?=(?:.*\d.*){10}$)\s*[.-]?\s*)?(?:\(?\s*(\d{3})\s*\)?\s*[.-]?))\s*(\d{3})\s*[.-]?\s*(\d{4})$/

The code sample (in Perl)

use strict;
use warnings;

my $rxphone = qr/
^
  (?:                         # Area code group (optional)
     \s*
     (?:
          1 (?=(?:.*\d.*){10}$)     # "1" (optional), must be 10 digits after it
         \s* [.-]?\s*
     )?
     (?: 
        \(?\s* (\d{3}|) \s*\)?      # Capture 1, 3 digit area code (optional)
        \s* [.-]?                   # ---  (999 is ok, so is 999)
     )
  )                           # End area code group
  \s*
  (\d{3})                     # The rest of phone number
  \s*
  [.-]?
  \s*
  (\d{4})
$
/x;

my %phonenumbs = (
 1 => '(123-456-7890',
 2 => '123.456-7890',
 3 => '456.7890',
 4 => '4567890',
 5 =>'(123) 456-7890',
 6 => '1 (123) 456-7890',
 7 => '11234567890',
 8 => ' (123) 4565-7890',
 9 => '1123.456-7890',
 w => '1-456-7890',
);

for my $key ( sort keys %phonenumbs)
{
    if ($phonenumbs{$key} =~ /$rxphone/) {
       print "#$key =>  '$1' '$2' '$3'\n";
    } else {
       print "#$key => not a valid phone number: '$phonenumbs{$key}' \n";
    }
}
__END__

Output
#1 => '123' '456' '7890'
#2 => '123' '456' '7890'
#3 => '' '456' '7890'
#4 => '' '456' '7890'
#5 => '123' '456' '7890'
#6 => '123' '456' '7890'
#7 => '123' '456' '7890'
#8 => not a valid phone number: ' (123) 4565-7890'
#9 => '123' '456' '7890'
#w => not a valid phone number: '1-456-7890'