Hey I'm doing a quick Perl script using Regex to identify certain phone # formats:
Formats that are valid:
(NNN) NNN-NNNN
(NNN)-NNN-NNNN
NNN-NNN-NNNN
Code:
#!/usr/bin/perl
use strict;
use warnings;
if (scalar @ARGV != 1) {
die "Usage: $0 <phone_number>\n";
}
my $string = $ARGV[0];
if ($string =~ m/^\(?\d{3}\)?[\s-]\d{3}[\s-]\d{4}$/) {
print "$string is valid\n";
print "Area: \n";
} else {
print "$string is not valid\n";
}
Currently I can identify the phone numbers, however I'm not sure how to extract the area code? Could I just do another regex and store that, or is there some trick with the $&/$1/$2/etc results array ?
EDIT:
Solved, not sure if the most efficient way. If anyone has an easier way I'd be keen to hear it.
Code:
#!/usr/bin/perl
use strict;
use warnings;
if (scalar @ARGV != 1) {
die "Usage: $0 <phone_number>\n";
}
my $string = $ARGV[0];
if ($string =~ m/^\(?\d{3}\)?[\s-]\d{3}[\s-]\d{4}$/) {
print "$string is valid\n";
$string =~ /^\(?\d{3}\)?/;
print "Area code: $&\n";
} else {
print "$string is not valid\n";
}