PDA

View Full Version : Anyone know Perl? Need a bit of help with reg exprs



*ClownPimp*
02-14-2003, 11:51 PM
can anyone tell me why second match operator doesnt find a match when the only difference between the two strings is the open brace at the end.


$_ = "ax bx : cx dx {";
$a = "ax";
$b = "(?:_)?\\w";
$c = "cx";
$d = "dx";
$str1 = "^$a\\s+(b)(?:\\s+:\\s+$c\\s+$b)?\\s*";
$str2 = "^$a\\s+(b)(?:\\s+:\\s+$c\\s+$b)?\\s*{";
print "1.".m/$str1/."\n";
print "2.".m/$str2/."\n";
print "\n";

Cela
02-15-2003, 10:52 AM
>>$str1 = "^$a\\s+(b)(?:\\s+:\\s+$c\\s+$b)?\\s*";
This pattern will match the following


ax bx : cx d

>>$str2 = "^$a\\s+(b)(?:\\s+:\\s+$c\\s+$b)?\\s*{";
So will this one, see the problem? :-) There's a left over x in the string that the regex doesn't handle, so the match fails. The reason the d is taken but not the x is here


$b = "(?:_)?\\w";

At the end you match a word character, this is the d :-) There're a bunch of ways to fix it as you'd expect with Perl, here's one


#!usr/bin/perl -w

$_ = "ax bx : cx dx {";
$a = "ax";
$b = "(?:_)?";
$c = "cx";
$d = "dx";

$str1 = "^$a\\s+(bx)(?:\\s+:\\s+$c\\s+$b$d)?\\s*";
$str2 = "^$a\\s+(bx)(?:\\s+:\\s+$c\\s+$b$d)?\\s*{";

print "1." . m/$str1/ . "\n";
print "2." . m/$str2/ . "\n";

*ClownPimp*
02-15-2003, 01:15 PM
Thanks :) As you can probably tell I'm new at this :p