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.


In reply to RE: Answer: How do I break down a phone number and rebuild it? by Ovid
in thread How do I parse a telephone number? by mofo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.