07. Greediness (continued)
- No. There is nothing to "force" the "(.*)" to give up anything it has matched. The "(.*)"
is greedy, and so it matches everything that it can, i.e. up to the end of the line,
just as before. Then the second ".*" gets its turn to match, and finds only the end of
the line, and so has to settle for matching nothing - which it can do, of course!
(because "*" means 0 or more times - and 0 here works). So, nothing changes.
- But what if we changed the regex to:
fanta(.*)drink
?
- Let's work through the example:
- First, the attempt to match f, then a, then .... etc. is tried. We'd end up matching:
This isn't fantastic, let's drink fanta!
^^^^^
- Then, it's ".*"'s turn, and of course, it's greedy! So, it would end up matching:
This isn't fantastic, let's drink fanta!
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- But, now we need to match a d! So, the ".*" is forced to give up some characters, resulting in the following:
This isn't fantastic, let's drink fanta!
^^^^^^^^^^^^^^^^^
- From here, the remaining 'd' and then "rink" part of the regex can match, giving the final match of:
This isn't fantastic, let's drink fanta!
^^^^^^^^^^^^^^^^^^^^^^
- With the $1 containing (in between the quotes):
"stic, let's "
|