Chapter 7. Quantifiers

You have already seen some quantifiers at work earlier in this book, but here I’ll talk about them in more detail.

For our example this time, we’ll use a Mac desktop application called Reggy (Figure 7-1), as we did in Chapter 5. Uncheck Match All at the bottom to start.

If you are not on a Mac, you can try these examples in one of the applications you’ve seen earlier in the book. Paste the right triangle of digits from the triangle.txt. The file is in the archive of examples.

Reggy application

Figure 7-1. Reggy application

Greedy, Lazy, and Possessive

I’m not talking about your teenager here. I’m talking about quantifiers. These adjectives may not sound like good character qualities, but they are interesting features of quantifiers that you need to understand if you want to use regular expressions with skill.

Quantifiers are, by themselves, greedy. A greedy quantifier first tries to match the whole string. It grabs as much as it can, the whole input, trying to make a match. If the first attempt to match the whole string goes awry, it backs up one character and tries again. This is called backtracking. It keeps backing up one character at a time until it finds a match or runs out of characters to try. It also keeps track of what it is doing, so it puts the most load on resources compared with the next two approaches. It takes a mouthful, then spits back a little at a time, chewing on ...

Get Introducing Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.