Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

How do I parse a telephone number?

by mofo (Acolyte)
on Jul 11, 2000 at 18:45 UTC ( [id://21984]=perlquestion: print w/replies, xml ) Need Help??

mofo has asked for the wisdom of the Perl Monks concerning the following question: (data formatting)

Users can enter free-form phone numbers, such as

212-555-1212 (212)555-1212 1-(212)-555-1212
How can extract just the essential numeric parts so that I can put the numbers into a uniform format?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I parse a telephone number?
by Anonymous Monk on Jul 11, 2000 at 21:29 UTC

    Here's an answer that allows the use of spaces instead of dashes, or no spacing at all.

    ( $areacode, $exchange, $line ) = $phn =~ m/(1[-| ]?)?\(?(\d{3})\)?[-| ]?(\d{3})[-| ]?(\d{4})/;
    Works on strings such as the following:
    212-555-1212 (212)555-1213 1-(212)-555-1214 1-212-555-1215 212 555 1216 (212) 555 1217 1 (212) 555 1218 1 212 555 1219 12125551210

      Actually, your regex, while good, has a slight problem. In a character class (something like [a-zA-Z]), the target text is filtered against each individual character in the class. No bar '|' for alternation is necessary. Your class actually is testing for a dash, a bar, and a space, rather than alternating between dash and space. Here's this code slightly cleaned up:
      #!/usr/local/bin/perl -w use strict; while (<DATA>) { s /[\n\r]//g; print "Testing with $_, result is "; m/(?:1[- ]?)? # Testing for an leading 1 and dash or space behi +nd it \(? # Optional parentheses around the area code (\d{3}) # Area code \)? # Close optional parentheses around area code [- ]? # Optional dash or space after area code (\d{3}) # Exchange [- ]? # Optional dash or space after exchange (\d{4}) # Line /x; # /x modifier allows whitespace in a regex my $areacode = $1; my $exchange = $2; my $line = $3; print "($areacode) $exchange-$line\n"; } __DATA__ 212-555-1212 (212)555-1213 1-(212)-555-1214 1-212-555-1215 212 555 1216 (212) 555 1217 1 (212) 555 1218 1 212 555 1219 12125551210
      A couple of notes on the code: when single character alternates are allowed (that's not quite the same thing as single byte alternates), a character class is much faster than alternation. In other words, we're using [- ] rather than (-| ).

      I also switched the first set of parentheses from (1[- ]?) to (?:1[- ]?). The (?:someregex) construct allows for grouping without backreferencing to a $somenumber variable. This is more efficient than straight parentheses for grouping and should be used, when possible.

Re: How do I parse a telephone number?
by mojotoad (Monsignor) on Jan 15, 2003 at 23:24 UTC
Re: How do I parse a telephone number?
by jlistf (Monk) on Jul 11, 2000 at 19:08 UTC

    ( undef, $areacode, $exchange, $line ) = $phn =~ m|(1-)?\(?(\d{3})\)?-?(\d{3})-(\d{4})|;
    You might want to do a little more error-checking on the number, but that's the idea.

Re: How do I parse a telephone number?
by chromatic (Archbishop) on Jul 12, 2000 at 00:28 UTC

    Here's a regex-less solution:

    sub parse_phonenumber { local $_ = shift; tr/()\- //d; # eliminate punctuation my( $are, $three, $four ); my $line = substr $_, -4, 4, ''; my $exch = substr $_, -3, 3, ''; my $area = substr $_, -3, 3, ''; ( $area, $exch, $line ) }
Re: How do I parse a telephone number?
by jdporter (Paladin) on Nov 17, 2006 at 14:20 UTC

    The only CPAN module that comes close to addressing the problem in a comprehensive way is the Number::Phone family of classes. They do a lot more than mere parsing; you may be particularly interested in their format method.

Re: How do I break down a phone number and rebuild it?
by jcwren (Prior) on Jul 11, 2000 at 19:20 UTC

    Based on jlistf's answer:

    ( undef, $areacode, $exchange, $line ) = $phn =~ m|(1-)?\(?(\d{3})\)?-?(\d{3})-(\d{4})|;
    Works on strings such as the following:
    212-555-1212 (212)555-1213 1-(212)-555-1214 1-212-555-1215

    Originally posted as a Categorized Answer.

Re: How do I break down a phone number and rebuild it?
by steveAZ98 (Monk) on Nov 18, 2000 at 00:45 UTC
    I take a slightly different approach because I have to deal with foreign phone numbers also. This sub seems to work pretty good for me. If it can't find a format it just splits it up into groups of threes and sends it back.
    HTH
    sub fphone { shift; s/[\s|\n|\r]//g; # strip space and newlines s/[-|)|(|.]//g; # strip seperating chars s/(x|ex|ext\.)(.*)$//; # Extension my $ext = $2; # save extension my $n = ''; my $l = length($_); if (($l == 12)||($l == 13)) { m/(\+\d{2}|\d{3})(\d{3})(\d{3})(\d{3})/; $n .= "$1 $2 $3 $4"; } elsif (length == 11) { # us with leading 1 s/[+]//g; m/(\D)?(\d{3})(\d{3})(\d{4})/; $n .= "$1 " if $1 =~ /\d/; $n .= "($2) $3-$4"; } elsif ($l == 10) { # us regular s/[+]//g; m/(\d{3})(\d{3})(\d{4})/; $n .= "($1) $2-$3"; } else { s/(\d\d\d)/$1 /g; $n .= $_; } $n .= " Ext. $ext" if $ext; return $n; }
      I might have tried to generalize that even further, though you still have regional issues to worry about. I.e. this won't work for everyone:
      @FORMAT_PHONE = ( '%d%d%d', # 911 '%d-%d%d%d', # 1-411 '%d-%d%d%d%d', # 5-1212 ? '%d%d-%d%d%d%d', # 55-1212 ? '%d%d%d-%d%d%d%d', # 555-1212 '%d-%d%d%d-%d%d%d%d', # 1-222-2345 '%d%d%d-%d%d%d-%d%d%d', # 212-114-151 ? '(%d%d%d) %d%d%d-%d%d%d%d', # (800) 555-1212 '+%d (%d%d%d) %d%d%d-%d%d%d%d', # +1 (800) 555-1212 '+%d%d (%d%d%d) %d%d%d-%d%d%d%d', # +01 (800) 555-1212 '+%d%d%d (%d%d%d) %d%d%d-%d%d%d%d', # +011 (800) 555-1212 '+%d%d%d %d (%d%d%d) %d%d%d-%d%d%d%d', # +011 1 (800) 555-1212 '%d%d%d%d%d (%d%d%d) %d%d%d-%d%d%d%d', # 10321 (800) 555-1212 '%d%d%d%d%d %d (%d%d%d) %d%d%d-%d%d%d%d', # 10321 1 (800) 555-1212 '%d%d%d%d-%d%d%d (%d%d%d) %d%d%d-%d%d%d%d', # 1010-220 (800) 555-12 +12 '%d%d%d%d-%d%d%d %d (%d%d%d) %d%d%d-%d%d%d%d', # 1010-220 1 (800) 5 +55-1212 # etc... ); my %L2M; @L2M{qw: Q Z :} = 1; @L2M{qw: A B C :} = 2; @L2M{qw: D E F :} = 3; @L2M{qw: G H I :} = 4; @L2M{qw: J K L :} = 5; @L2M{qw: M N O :} = 6; @L2M{qw: P R S :} = 7; # some define this as PQRS @L2M{qw: T U V :} = 8; @L2M{qw: W X Y :} = 9; # some define this as WXYZ sub format_phone { my $number = shift; $number =~ s/[a-zA-Z]/$L2M{uc($1)}/eg; $number =~ s/\D//g; # maybe allow # and * later?? if (defined($FORMAT_PHONE[length($number)-3])) { return sprintf($FORMAT_PHONE[length($number)-3], split(//, $numb +er)); } return; }
Re: How do I break down a phone number and rebuild it?
by Anonymous Monk on Jul 11, 2000 at 19:54 UTC
    Both your replies work wonderful. Thanks for helping me learn regex as well as fixing my problem.

    Originally posted as a Categorized Answer.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://21984]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (4)
As of 2024-04-19 01:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found