Regular expression in Perl

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sakshismriti
    New Member
    • May 2010
    • 5

    #1

    Regular expression in Perl

    I have a regex which extratcs the name from it.

    The code is given below:
    Code:
    # Extract some parts from regex
    $input = "Hello, Shane !";
    $pattern = "^Hello, \\w+\\s*!\$";
     
    if($input =~ /$pattern/) {
    	print "\nThe input matches the pattern The dollar variables are\n";  
    	print " \nONE == $1";
    	print "\n";
    }
    
    The input matches the pattern The dollar variables are  
    ONE == Shane
    Now, if I want to extract the name, like this :

    Problem:
    Now, I'd like to match the earlier, and get the extracted data ("Shane" here in our example) by a designated name, not a number set by the regex.

    Eg.:

    ^Hello, (?{surname}\w+) \s*!$

    then I'll have a way to get the extracted data into $surname or maybe there is a way to do something like this:
    Code:
    my $input = "Hello, Shane !";
    my $regex = '^Hello, (?{surname}\w+)\s*!$'
    my %match = Regex.match($regex, $input);
    $match{"surname"} == "Shane"; # true
    Regex.match() is the sub routine name given by me(dont confuse with any existing in built module in Perl).
    It is this sub routine which has the functionality of matching the regex and returning the extracted data in the parameter surname.


    Any help is highly appreciated.

    Thanks.

    Regards,
    Sakshi
    Last edited by sakshismriti; May 27 '10, 09:18 AM. Reason: change in code
  • toolic
    Recognized Expert New Member
    • Sep 2009
    • 70

    #2
    Update: As Sakshismriti discovered, named regex captures are now possible as of Perl version 5.10.0.


    Original reply:
    I think you must use the special number variables, but that's not a bad thing:

    Code:
    use strict;
    use warnings;
    use Data::Dumper;
    
    my $input   = 'Hello, Shane !';
    my $pattern = qr{^Hello, (\w+)\s*!$};
    my %match;
    if ($input =~ /$pattern/) {
        $match{surname} = $1;
    }
    
    print Dumper(\%match);
    
    __END__
    
    $VAR1 = {
              'surname' => 'Shane'
            };

    Comment

    • sakshismriti
      New Member
      • May 2010
      • 5

      #3
      Thanks for the help.
      I have also made another solution for me and it is working fine :

      Code:
      #!/opt/perl/bin/perl
      
      # Test regex with surname 
      my $input_string = "Hello, Shane !";
      my $regex_string = "^Hello, (?{surname}\\w+)\\s*!\$";
      
      my  %match = match($regex_string, $input_string);
      if ($match{"code"} != 0) { 
      	print $match{"error_msg"};
      } else {
      	print "\nExtracted string is: [". $match{"surname"}. "]\n";
      }
      
      # Test regex with another word called color in place of surname    
      # I made another input string and regex for it 
      $input_string = "The, red cherries !";
      $regex_string = "^The, (?{color}\\w+)\\s*\\w+\\s*!\$";
      
      %match =  match($regex_string, $input_string);
      if ($match{"code"} != 0) { 
      	print $match{"error_msg"};
      } else {
      	print "\nExtracted string is: [". $match{"color"}. "]\n";
      }
      
      # Test above regex non matching pattern      
      # I made another input string and regex for it 
      $input_string = "The red cherries !";
      $regex_string = "^The, (?{color}\\w+)\\s*\\w+\\s*!\$";
      
      %match =  match($regex_string, $input_string);
      if ($match{"code"} != 0) { 
      	print $match{"error_msg"};
      } else {
      	print "\nExtracted string is: [". $match{"color"}. "]\n";
      }
       
      sub match () {
      	my $regex = shift();
      	my $input = shift();
      	
      	my %return = ();
      	my $param_name;
      	# Extract the name of return type from regex
      	if($regex =~ s/\?{(.+)}//) { 
      		$param_name = $1; 
      	
      	} else {
      		$return{"code"} = 1;
              $return{"error_msg"} = "Improper regex [$regex] given as input.";
              return %return;
      	}
      	 
      	# Compare input with the regex
      	if($input =~ /$regex/) {
      		$return{"code"} = 0;
      		$return{$param_name} = $1;
      		return %return;
      	} else {
      		$return{"code"} = 1;
      		$return{error_msg} = "There are no match corresponding to your search.";
      		return %return;
      	}
      }
      Regards,
      Sakshi

      Comment

      • sakshismriti
        New Member
        • May 2010
        • 5

        #4
        Originally posted by sakshismriti
        I have a regex which extratcs the name from it.

        The code is given below:
        Code:
        # Extract some parts from regex
        $input = "Hello, Shane !";
        $pattern = "^Hello, \\w+\\s*!\$";
         
        if($input =~ /$pattern/) {
        	print "\nThe input matches the pattern The dollar variables are\n";  
        	print " \nONE == $1";
        	print "\n";
        }
        
        The input matches the pattern The dollar variables are  
        ONE == Shane
        Now, if I want to extract the name, like this :

        Problem:
        Now, I'd like to match the earlier, and get the extracted data ("Shane" here in our example) by a designated name, not a number set by the regex.

        Eg.:

        ^Hello, (?{surname}\w+) \s*!$

        then I'll have a way to get the extracted data into $surname or maybe there is a way to do something like this:
        Code:
        my $input = "Hello, Shane !";
        my $regex = '^Hello, (?{surname}\w+)\s*!$'
        my %match = Regex.match($regex, $input);
        $match{"surname"} == "Shane"; # true
        Regex.match() is the sub routine name given by me(dont confuse with any existing in built module in Perl).
        It is this sub routine which has the functionality of matching the regex and returning the extracted data in the parameter surname.


        Any help is highly appreciated.

        Thanks.

        Regards,
        Sakshi
        Hey,

        I got the more appropriate solution, I have to use labelled capturing groups in perl which is new in Perl 5.0
        Read it here :
        Learning Perl, popularly known as "the Llama," is the book most programmers rely on to get started with Perl. The bestselling Perl tutorial since it was first published in 1993, this new fifth edition covers recent changes to the language up to Perl 5.10. This book reflects the combined experience of its authors, who have taught Perl at Stonehenge Consulting since 1991. Years of classroom testing and experience helped shape the book's pace and scope, and this edition is packed with exercises that let you practice the concepts while you follow the text. Topics include:Perl data & variable typesSubroutinesFile operationsRegular expressionsString manipulationLists & sortingProcess managementSmart matchingUsing third party modulesPerl is the language for people who want to get work done. Originally targeted to sysadmins for heavy-duty text processing, Perl is now a full-featured programming language suitable for almost any task on almost any platform-from short fixes on the command line to web applications, bioinformatics, finance, and much more. Other books may teach you to program in Perl, but this book will turn you into a Perl programmer.


        The solution is as follows:
        Code:
        #!/usr/bin/perl -w
        use strict;
        use Data::Dumper; # for debug only
        
        my $input = 'Hello, Shane !';
        my $regex = qr/^Hello, (?<surname>\w+)\s*!$/;
        my %match = match($regex, $input);
        # print("\nthis is match" . Dumper(%match));
        print ("\n The matched value ios === ". $match{"surname"});	
        # $match{surname} eq 'Shane'; # true
        
        
        sub match {
           $_[1] =~ $_[0];
           map { $_ => $+{$_} } keys %+;
        }
        Cheers!!!
        Sakshi

        Comment

        Working...