> -----Original Message-----
> From: Chris Stinemetz [mailto:[email protected]]
> Sent: Tuesday, December 20, 2011 9:22 AM
> To: Saravanan Murugaiah
> Cc: [email protected]
> Subject: Re: Help in search concept
> 
> >
> > I am a learner in Perl and this is my first post in this group. I
> need
> > to search a word "Test 1.2.1" in my file. I am using "$_ =~m/Test
> > \d+", but it searched only "Test 1" not the full content. I need to
> > check whether it is "Test 1" or "Test 1.2" or "Test 1.2.1". Kindly
> > help me in this regard
> >
> 
> Hello MadYuv,
> 
> I'm sure there is a much cleaner way of writing the regular expression.
> I am in the process of learning regular expression Perl flavour myself.
> 
> Below is sample program I came up with below:
> 
> HTH,
> 
> Chris
> 
> #!/usr/bin/perl
> use warnings;
> use strict;
> 
> while(<DATA>) {
>   chomp;
>   if($_ =~ m/(Test\s+\d\.\d\.\d)/){
>     print "$1\n";
>   }
> }
> 
> __DATA__
> Test 1.2.1
> Test 1.2.1
> Test 1.2.1
> Test 1.2.1
> Test 1
> Test 1.2
> 
> ***OUTPUT***
> Test 1.2.1
> Test 1.2.1
> Test 1.2.1
> Test 1.2.1
> 

Hi Chris,
Note that your regular expression requires that 'Test' be followed by
whitespace and then exactly one digit followed by a period followed by a
single digit followed by a period followed by another single digit.
It does not account for '1' or '1.2'. Also, although the OP does not
specify, the numbers could be more that single digits.
Below I give an example using a quoted regular expression with the 'x'
modifier to allow comments and whitespace (including newlines) to be ignored
- the better to document what you are trying to accomplish. 
HTH,
Ken

use strict;
use warnings;

my $matchRE = qr/
                 (  #  Start grabbing $1
                   Test  #  Literal 'Test'
                   \s+   # one or more whitespace characters
                   \d+   # one or more numeric characters
                   (?:   # Do not capture match in parentheses
                      \.    # literal period|dot character
                      \d+   # one or more numeric characters
                   )*    # match in parentheses is optional 
                         # and can occur multiple times
                 )  #  End of parentheses capturing $1
                /x;

while(<DATA>) {
  chomp;
  if(/$matchRE/) {
    print "$1\n";
  }
}

__DATA__
Test 1.2.1
Test 1.2.12
Test 1.21.1
Test 1.21.12
Test 1.21.12.1
Test 1
Test 1.2







-- 
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/


Reply via email to