Skip to Content
Perl in a Nutshell, 2nd Edition
book

Perl in a Nutshell, 2nd Edition

by Nathan Patwardhan, Ellen Siever, Stephen Spainhour
June 2002
Beginner content levelBeginner
759 pages
80h 42m
English
O'Reilly Media, Inc.
Content preview from Perl in a Nutshell, 2nd Edition

Quantifiers

Quantifiers are used to specify the number of instances of the previous element that can match. For instance, you could say “match any number of a’s, including none” (a*), or “match between 5 and 10 instances of the word `owie’ ((owie){5,10})”.

Quantifiers, by nature, are greedy. That is, the way the Perl regular expression “engine” works is that it will look for the biggest match possible (the farthest to the right) unless you tell it not to. Say you are searching a string that reads:

a whatever foo, b whatever foo

and you want to find a and foo with something in between. You might use:

/a.*foo/

A . followed by a * looks for any character, any number of times, until foo is found. But since Perl will look as far to the right as possible to find foo, the first instance of foo is swallowed up by the greedy .* expression.

Therefore, all the quantifiers have a notation that allows for minimal matching, so they are nongreedy. This notation uses a question mark immediately following the quantifier to force Perl to look for the earliest available match (farthest to the left). The following table lists the regular expression quantifiers and their nongreedy forms:

Maximal

Minimal

Allowed range

{n,m}

{n,m}?

Must occur at least n times but no more than m times

{n,}

{n,}?

Must occur at least n times

{n}

{n}?

Must match exactly n times

*

*?

0 or more times (same as {0,})

+

+?

1 or more times (same as {1,})

?

??

0 or 1 time (same as {0,1})

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Advanced Perl Programming

Advanced Perl Programming

Sriram Srinivasan

Publisher Resources

ISBN: 0596002416Errata Page