Search code examples
regexperl

Perl match and extract phone number with (312) 555-1212 format


Trying to get perl to recognize and extract a phone number in a string with some odd formatting that is found in a file:

my $str = 'Phone:

(312) 555-1212 _
';

I tried but this solution but it winds up extracting all numbers from strings:

my @all_nums = $element =~ /(\d+)/g; 
  
 if (@all_nums) {
        
    my $ph = join('-', @all_nums);
    print "PHONE NO: $ph\n"; 
        
    push(@elements_found, $ph);
            
}

Any help is greatly appreciated.


Solution

  • Try a more precise regex for the number format:

    my @all_nums = $element =~ /\((\d+)\) (\d+)-(\d+)/g; 
      
     if (@all_nums) {
            
        my $ph = join('-', $1, $2, $3);
        print "PHONE NO: $ph\n"; 
            
        push(@elements_found, $ph);
                
    }