Perl - Use of *? in Matching Pattern

I am using Perl version 5.8.4 and trying to understand the use of regular expression. Following is my code and output.

 
 $string = "Perl is a\nScripting language";
 ($start) = ($string =~ /\A(.*?) /);
 @lines = ($string =~ /^(.*?) /gm);
 print "First Word (using \\A): $start\n","Line Starts (using ^): @lines\n";
 

Output:-
First Word (using \A): Perl
Line Starts (using ^): Perl Scripting

I know

  • (star) is used to 'Matches 0 or more occurrence of preceding expression'.
    ? (question mark) is used to 'Matches 0 or 1 occurrence of preceding expression'.

But I did not understand how both (*?) are working together in above piece of code.

Thanks!

As far as I can tell the question mark would be meaningless. What is "zero or one" of "zero or more characters"? At first I thought it might be one of perl's weird look-ahead or look-behind operators, but those start with a question mark, not end.

Actually, Perl regexen have the concept of reluctant quantifiers, thus /<.*>/ will match all of <img src="http://linux.unix.com/images/next.gif" alt="Next>"> whereas /<.*?>/ will match <img src="http://linux.unix.com/images/next.gif" alt="Next>

1 Like

AKA lazy matching as opposed to greedy matching

1 Like

Hi.

       By default, a quantified subpattern is "greedy", that is, it will match
       as many times as possible (given a particular starting location) while
       still allowing the rest of the pattern to match.  If you want it to
       match the minimum number of times possible, follow the quantifier with
       a "?".  Note that the meanings don't change, just the "greediness":

           *?     Match 0 or more times, not greedily
           +?     Match 1 or more times, not greedily
           ??     Match 0 or 1 time, not greedily
           {n}?   Match exactly n times, not greedily
           {n,}?  Match at least n times, not greedily
           {n,m}? Match at least n but not more than m times, not greedily

-- from perlre: perldoc perlre , or man perlre q.v.

Best wishes ... cheers, drl

1 Like