Regular expressions

Greediness and Laziness


Given the HTML text from the previous example, let us now try to extract all the text that is inside the <A HREF=".."> tag.

We would like to get the result

A HREF="index.html"
However, note that the following code will retrieve more than that:

my $html = "List of <A HREF=\"index.html\">Lecture Slides</A>.";

$html =~ /<(.*)>/;

print "$1\n";
A HREF="index.html">Lecture Slides</A


The * quantifier (as well as the +) is greedy, i.e. it will try to capture as much as it can before it is restricted to match the rest of the regular expression.

In the example above, it matched all the text until the last > sign of the HTML text, and not until the closest one.

To force the quantifier to be lazy and capture the minimum it can before the rest of the regular expression, write a question mark ? after it.


The correct regular expression for the example above is thus:
$html =~ /<(.*?)>/;

Table of Contents.