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.