Ungreedy Matching with *? and Friends

Contents | Up | Prev | Next

# 7.7.2. Ungreedy Matching with *? and Friends

By defualt, 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:

    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";

Contents | Up | Prev | Next