Thread: Perl Regex

Results 1 to 2 of 2
  1. #1 Perl Regex 
    Respected Member


    Join Date
    Jul 2015
    Posts
    781
    Thanks given
    206
    Thanks received
    394
    Rep Power
    524
    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";
    }
    Reply With Quote  
     

  2. #2  
    Programmer, Contributor, RM and Veteran




    Join Date
    Mar 2007
    Posts
    5,147
    Thanks given
    2,656
    Thanks received
    3,731
    Rep Power
    5000
    Use brackets to make a capturing group, then you can use $1:

    Code:
    if ($string =~ m/^\(?(\d{3})\)?[\s-]\d{3}[\s-]\d{4}$/) {
    	print "$string is valid\n";
    	print "Area code: $1\n";
    .
    Reply With Quote  
     

  3. Thankful user:



Thread Information
Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)


User Tag List

Similar Threads

  1. Perl. tut
    By HaVoK0321 in forum Application Development
    Replies: 4
    Last Post: 02-04-2010, 07:13 AM
  2. [Perl] Boredom
    By R3KoN in forum Application Development
    Replies: 2
    Last Post: 02-01-2010, 07:38 PM
  3. Regex Yo Strings
    By bloodargon in forum Tutorials
    Replies: 7
    Last Post: 09-06-2009, 02:40 AM
  4. Regex Splitting
    By Pride in forum Help
    Replies: 5
    Last Post: 08-01-2009, 04:54 PM
  5. [PERL] Rapidshare Downloader
    By gbawlz in forum Application Development
    Replies: 1
    Last Post: 11-22-2008, 10:44 PM
Posting Permissions
  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •