Perl Regular expression

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Perl Regular expression

Sujay
Hi Guru,

Could you please let me know what is wrong with the below code snippet. Ideally, it should return me the matched value in the perl special variable, but the output returned is "not found" instead.

#!/usr/bin/perl
use warnings;

my $x = "<name>Perl</name>";

if ($x =~ m/([a-z][A-Z]+).*/){
        print $1;
}else{
        print "not found\n";
}
Reply | Threaded
Open this post in threaded view
|

Re: Perl Regular expression

Sujay
Modified the code as below, inorder to match the first tag name. However, the output still remains the same - "not found".

#!/usr/bin/perl
use warnings;

my $x = "<name>Sujay</name>";

if ($x =~ m/.*?>([a-z][A-Z]+).*/){
        print $1;
}else{
        print "not found\n";
}
Reply | Threaded
Open this post in threaded view
|

Re: Perl Regular expression

Sujay
I got it working :-). There was a syntax error in the code. [a-z][A-Z] should have been [a-zA-z]. Interestingly, perl didn't notify me of this syntax error. Any thoughts?

Thanks in advance
Sujay
Reply | Threaded
Open this post in threaded view
|

Re: Perl Regular expression

Guru
Administrator
Hi Sujay
   Actually, there was no syntax error in your earlier code.  Reg ex : [a-z][A-Z]+ is a valid expression which will match a word in which first letter is a smaller case alphabet([a-z]) and the remaining are upper case([A-Z]+).  Keep in mind anything in square brackets match one character. So, [a-z] matches one lower case character, and [A-Z]+ matches a sequence of upper case characters.  Hope I helped you.

Guru.