http://qs321.pair.com?node_id=28630

Carl-Joseph has asked for the wisdom of the Perl Monks concerning the following question:

My friends and I have been playing around with regular expressions, and we ran into something that we haven't been able to explain.

Here is some test code that shows the "phenomena".

#! G:\Perl\bin\perl.exe $test_string="x"; # # This pattern matches once, and it matches # after the "x", not before. # @test = ($test_string =~ /^x*/g ); $NumMatch=@test; print "Test String\t>$test_string<\n"; print "Prematch\t>$`<\n"; print "Match\t\t>$&<\n"; print "Postmatch\t>$'<\n"; print "Num Matches\t>$NumMatch<\n"; print "Match Arrary:\n"; foreach $m (@test) { print ">$m<\n"; } print "\n"; print "-" x 10; print "\n\n"; # # This pattern matches twice, and # the second match is after the "x" # @test = ($test_string =~ /x*$/g ); $NumMatch=@test; print "Test String\t>$test_string<\n"; print "Prematch\t>$`<\n"; print "Match\t\t>$&<\n"; print "Postmatch\t>$'<\n"; print "Num Matches\t>$NumMatch<\n"; print "Match Arrary:\n"; foreach $m (@test) { print ">$m<\n"; } __END__

The above code produces the following output.

Test String >x< Prematch >x< Match >< Postmatch >< Num Matches >1< Match Arrary: >x< ---------- Test String >x< Prematch >x< Match >< Postmatch >< Num Matches >2< Match Arrary: >x< ><

Here is why we are confused:

Why does the first pattern match after the "x". I understand that "x*" is able to match nothing, but shouldn't it match the nothing before the "x", rather than the nothing after the "x".

The reason I think it should match before the "x" is that I use the "^" assertion. Also, Camel2, p61 says:

"... any regular expression that can match the null string is guaranteed to match at the leftmost position in the string."

Also, why does the second pattern "x*$" match twice when the first pattern matched only once. It seems as though they should either both match once or both match twice.

Thanks,

Carl-Joseph