"Perl for Perl Newbies" - Part 2Regular ExpressionsSubstituting using Regular ExpressionsUngreedy Matching with *? and Friends

7.7.2. Ungreedy Matching with *? and Friends

By default, the regular expression repetition operators such as *, + and friends are greedy. Hence, they will try to match as much as possible of the string as they can.

If you wish them to match as little as possible, append a question mark (?) after them. Here's an example:

use strict;
use warnings;

my $string = "<html>Hello</html>You</html>";

my $greedy = $string;
$greedy =~ s/<html>.*<\/html>/REPLACED/;

my $ungreedy = $string;
$ungreedy =~ s/<html>.*?<\/html>/REPLACED/;

print $string, "\n",
    $greedy, "\n",
    $ungreedy, "\n";

Written by Shlomi Fish