In the last lesson, [0-9] took only one digit, so $85.00 broke into four results. To get the whole price, a pattern needs a way to say "there can be many digits".
Mrs. Ratna's PO form has rules like that: "tarts, at least 1 jar", "a greeting card, optional", "at most 5 jars per person". The rules don't name the item, only the amount, and each one applies to the item named right before it. In a regex, a rule about amounts is called a quantifier: it sets how many times the thing right in front of it may repeat. Without a quantifier, every part of a pattern matches exactly once.
A quantifier repeats the one thing in front of it
| Quantifier | Meaning | Example from the chat |
|---|---|---|
? |
0 or 1 time (optional) | -? a dash may be there |
* |
0 or more times | 07\d* |
+ |
1 or more times | \d+ |
{4} |
exactly 4 times | PO-\d{4} |
{10,13} |
10 to 13 times | \d{10,13} |
{2,} |
at least 2 times | \d{2,} |
console.log(chat.match(/\$\d/g)); // ['$8', '$1', '$1']
console.log(chat.match(/\$\d+/g)); // ['$85', '$165', '$170']
console.log(chat.match(/\d+ dollars/g)); // ['90 dollars', '255 dollars']
\$\dwith no quantifier: a dollar sign (\$, escaped) then one digit. The result is cut short:$8.\$\d+:+repeats\das many times as it can, so the price comes out whole.\d+ dollars: one or more digits, a space, then the worddollars. The prices written with a word are found too.- A quantifier repeats only the one thing right in front of it.
/PO+/repeats just the letterO, notPO.
?, * and + in phone numbers
console.log(chat.match(/07\d+/g)); // ['07700', '07700900461']
console.log(chat.match(/07\d*/g)); // ['07', '07', '07700', '07', '07', '07', '07700900461', '07']
console.log(chat.match(/07\d{3}-?\d{3}-?\d{3}/g)); // ['07700-900-123', '07700900461']
07\d+asks for at least one digit after07. In Dina's number the digits stop at the dash, so only07700.07\d*allows zero digits. The time07.15on every line is found as07too, because*is satisfied with zero digits.-?means the dash may or may not be there. One pattern catches both07700-900-123and07700900461.
Exact counts: {n}, {n,m}, {n,}
console.log(chat.match(/07\d{9}/g)); // ['07700900461']
console.log(chat.match(/\d{10,13}/g)); // ['1234567890', '07700900461']
console.log("aabbb".match(/ab{2,3}/)[0]); // 'abbb'
07\d{9}:07then exactly 9 digits, so an 11-digit number with no dashes, the length of a UK mobile number.\d{10,13}also catches the bank account1234567890, because the pattern only counts digits. How to tell them apart comes in the Anchors lesson.{n,}means at least n times, with no upper limit.{,3}doesn't exist in JavaScript:/a{,3}/looks for the texta{,3}as it is.ab{2,3}inaabbb: 2 or 3 b's are allowed, and the quantifier takes as many as it can, so the result isabbb.
Greedy and lazy
The chat's first line has three bold texts, WhatsApp style: *Tart*, *Cheese Sticks*, *Snowballs*. The pattern \*.+\* means "an asterisk, anything, an asterisk". Does it take one text, all three separately, or one long piece? Hold on to your guess and read on.
Quantifiers are greedy: they take as much as they can first, then back off bit by bit if the rest of the pattern doesn't fit.
console.log(chat.match(/\*.+\*/g)); // ['*Tart* $85/jar, *Cheese Sticks* 90 dollars, *Snowballs*']
console.log(chat.match(/\*.+?\*/g)); // ['*Tart*', '*Cheese Sticks*', '*Snowballs*']
console.log("aXXbXX".match(/X+/g)); // ['XX', 'XX']
console.log("aXXbXX".match(/X+?/g)); // ['X', 'X', 'X', 'X']
\*.+\*:.+eats to the end of the line, then backs off until it finds the last*. The result is one long piece from*TarttoSnowballs*.- A
?after a quantifier makes it lazy: take as little as possible.\*.+?\*stops at the next*, so each bold text comes out separately. X+?is happy with oneX, so withgthe result is four singleXs.- The same goes for HTML:
"<b>bold</b> and <i>italic</i>".match(/<.+>/)[0]takes the whole text, while/<.+?>/ggives['<b>', '</b>', '<i>', '</i>'].
⚠️ Quantifiers that grab too much, or the wrong thing
*matches empty text./\d*/.test("hello")givestrue, because zero digits count as a match, and"hello".match(/\d*/)gives['']at index 0. When at least one is required, use+.- Forgetting a quantifier repeats one thing only.
/ha+/matcheshaaa, nothahaha. Repeating several characters at once needs a group, covered in the Groups lesson. - Greedy across repeated text.
.+between two delimiters often eats too much. Use the lazy.+?, or a class that refuses the delimiter:\*[^*]+\*. - A quantifier with nothing in front of it.
new RegExp("*Tart*")is rejected:Invalid regular expression: /*Tart*/: Nothing to repeat. Written directly as/*Tart*/, JavaScript reads it as a comment instead, because/*starts a comment. Want the asterisk itself?\*.
TL;DR: A quantifier sets how many times the thing right in front of it repeats: ? 0 or 1, * 0 or more, + 1 or more, {n} exactly n, {n,m} between n and m, {n,} at least n. Quantifiers are greedy: "aabbb".match(/ab{2,3}/)[0] gives abbb, and \*.+\* swallows everything from the first asterisk to the last. Add ? for lazy: \*.+?\* takes each bold text, X+? one X per result. * can match zero characters, so test() with \d* is always true.
⚡ A quantifier repeats the one thing in front of it
Write:
console.log(chat.match(/\$\d+/g)); // ['$85', '$165', '$170']
Meaning: ? 0 or 1, * 0 or more, + 1 or more, {n} exactly n, {n,m} between n and m. Without the +, \d takes only one digit: $8.
⚡ Greedy: take as much as it can
Write:
console.log("aabbb".match(/ab{2,3}/)[0]);
Guess first: 2 or 3 b's are allowed. Is the result abb or abbb?
abbb. Quantifiers are greedy: they take as much as they can first, and only back off when the rest of the pattern doesn't fit.
Meaning: A quantifier starts from the most. \*.+\* swallows one long piece, from the first asterisk on the line to the last.
⚡ Lazy: add a ?
Write:
console.log(chat.match(/\*.+?\*/g)); // ['*Tart*', '*Cheese Sticks*', '*Snowballs*']
Meaning: A ? after a quantifier makes it lazy: it takes as little as possible, so each bold text comes out on its own.