found, a reluctant quantifier continues to add characters from the string until either a match is found or
the entire string is checked without a match. Reluctant quantifiers work in reverse of greedy quantifiers.
only tries to match against the entire string. If the entire string doesn’t produce a
match, no further attempt is made. Possessive quantifiers are, in a manner of speaking, a one-shot deal.
What makes a quantifier greedy, reluctant, or possessive? It’s really all in the use of the asterisk, question
mark, and plus symbols. For example, the question mark alone (
) is greedy, but a question mark fol-
lowed by another question mark (
) is reluctant. To make the question mark possessive, append a plus
). The following table shows all the greedy, reluctant, and possessive versions of the quantifiers
you’ve already learned.
Zero or one occurrences
Zero or more occurrences
One or more occurrences
but no more than
To illustrate the differences among the three kinds of quantifiers, consider the following example:
var sToMatch =”abbbaabbbaaabbb1234”;
var re1 = /.*bbb/g; //greedy
var re2 = /.*?bbb/g; //reluctant
var re3 = /.*+bbb/g; //possessive
You want to match any number of letters followed by
. Ultimately, you’d like to get back as matches
. However, only one of the three regular expressions returns this result,
can you guess which one?
If you guessed
, congratulations! You now understand the difference between greedy, reluctant, and
possessive quantifiers. The first regular expression,
, is greedy and so it starts by looking at the
whole string. Behind the scenes, this is what happens:
re1.test(“abbbaabbbaaabbb1234”); //false - no match
re1.test(“abbbaabbbaaabbb123”); //false - no match
re1.test(“abbbaabbbaaabbb12”); //false - no match
re1.test(“abbbaabbbaaabbb1”); //false - no match
re1.test(“abbbaabbbaaabbb”); //true – match!
So the only result that
. Remember, the dot represents any character,
is included, therefore
part of the expression and
10_579088 ch07.qxd 3/28/05 11:38 AM Page 203