B.2 Quantifiers
A quantifier is a
metacharacter that tells
"how many." You put a quantifier
after an item to indicate you want to match that item a certain
number of times. Quantifiers are listed in Table B-1.
Table B-1. Quantifiers
Quantifier
|
How many times
|
---|
*
|
Zero or more
|
+
|
One or more
|
?
|
Optional (zero or one)
|
{x}
|
Exactly x
|
{x,}
|
At least x
|
{x,y}
|
At least x, but no more than
y
|
To use a quantifier, put it immediately after the item you want to
quantify. Table B-2 shows some regular expressions
with quantifiers.
Table B-2. Quantifier examples
Regular expression
|
Meaning
|
Matches
|
Doesn't match
|
---|
ba+
|
b, then at least one a
|
ba, baa,
baaa, rhumba,
babar
|
b, abs,
taaa-daaa, celeste
|
ba+na*s
|
b, at least one a,
n, zero or more a,
s
|
turbans, baanas,
rhumbanas!
|
banana, bananas
|
ba(na){2}
|
ba, then na twice
|
banana, bananas,
semi-banana, bananarama
|
cabana, banarama
|
ba{2,}ba{3,}
|
b, then at least two a, then
b, then at least three a
|
baabaaa, baaaaabaaaaa,
rhumbaabaaas
|
baabaa, babaaar,
banana
|
(baa-){2,4}baa
|
baa- at least two, but not more than four times,
then baa
|
baa-baa-baa,
baa-baa-baa-baa-baa,
oomp-pa-pa-baa-baa-baa-oomp-pa-pa
|
baa-baa, baa-baad-news
|
dogs? and cats?( and chickens?)?
|
dog, then an optional s, then
and cat, then an optional s,
then an optional and chicken or
and chickens
|
dog and cat and chicken,
dog and cat and chickens,
hotdogs and cats, dogs
and cat and chickens,
dog and cats and chicken,
dog and cat and chickensoup
|
doggies and cats, dogs
and cats or chickens,
dogss and catss,
dog and cat and chickenlegs
|
Use the ? quantifier to indicate that something is
optional, like in the U.S. ZIP Code pattern at the start of this
appendix. A syntactically valid ZIP Code can be five digits, or five
digits, a hyphen, and four more digits. The hyphen and last four
digits are optional. Just like any other quantifier, to make
? apply to the entire optional section, the
characters that match the hyphen and digits have to be grouped with
parentheses.
|