04. The earliest match wins (continued)
- So what? Well, if you were greping a file, you wouldn't care, because the line would be displayed either way,
but you would care if you didn't like fanta, and you preferred lemon twist, because:
#!/usr/bin/perl
$string = "This isn't fantastic, let's drink fanta!";
$string =~ s/fanta/lemon twist/;
print "$string\n"
gives the result:
This isn't lemon twiststic, let's drink fanta!
- Similarly, if you used the regular expression:
fantastic|drink|is
You would match:
This isn't fantastic, let's drink fanta!
^^
- Why? Remember, our simplified regex engine is following our two rules, and rule one is that the
earliest match wins - so the entire regex is tried at each position as it "bumps" along.
Thus, "fantastic" is tried at the start, then "drink",
then "is", and when none match, the engine moves along one position, and it tries it all again,
until it gets to
the "is" in "This" where a match is found! It's the earliest match that wins.
|