Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: How do I parse a telephone number?

by Anonymous Monk
on Jul 11, 2000 at 21:29 UTC ( [id://22040]=note: print w/replies, xml ) Need Help??


in reply to How do I parse a telephone number?

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

Replies are listed 'Best First'.
RE: Answer: How do I break down a phone number and rebuild it?
by Ovid (Cardinal) on Jul 11, 2000 at 22:06 UTC
    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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (8)
As of 2024-04-19 09:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found