Thursday, September 26, 2013

What do lazy and greedy regular expressions mean?

Greedy expression tries to get as much as possible.
If you write a regular expression like this
<.+>
for the string:
<p>My expression</p>
you will get all the string
<p>My expression</p>
Oh, yes.. this thing is really greedy.

Let's take a look at the lazy one. If you write a regular expression like
<.+?>
We have just added "?". That means we want the smallest possible group. Now we have this result:
<p>
Here you are. The laziest thing you have ever seen :)