Counted repetition

Beginner · 9 min

{n}, {n,} and {n,m} set an exact count or a range. Build ZIP codes and hex colours with them, and see why {,3} and a stray { behave differently across flavours.

Before thisQuantifiers: star, plus and question

Kris Jordan · 10 min

Counted repetition

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Kris JordanReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • {n} means exactly n, {n,} means n or more and {n,m} means between n and m inclusive. * is {0,}, + is {1,} and ? is {0,1}.
  • A range is greedy: /\d{2,4}/ on '12345' matches '1234'. Anchor the pattern with ^ and $ when the count must be exact.
  • A count applies to one item, so (ab){2} is abab and ab{2} is abb. Put the item in a group to repeat a sequence.
  • {,3} is a quantifier in Python 3.9 and recent Perl and PCRE, but literal text in JavaScript and in macOS grep -E. Write {0,3} everywhere.
  • A { that does not form a valid count is literal in JavaScript's default mode, and an error with the u flag. Escape it as \{ when you mean a brace.

When “some” is not precise enough

*, + and ? count loosely: any number, at least one, maybe one. Plenty of formats are stricter. A US ZIP code is exactly five digits. A short hex colour is three, a long one is six. A year is four digits. You could write \d\d\d\d\d, but that is hard to read and impossible to scale, so curly braces say the count directly. A number or a pair of numbers between { and } comes right after the thing being repeated:

  • {5} means exactly 5.
  • {3,} means 3 or more.
  • {2,4} means between 2 and 4, inclusive.

The earlier quantifiers are special cases. * is {0,}, + is {1,} and ? is {0,1}.

A pattern that only accepts what you meant

Exact counts shine with anchors. I ran each of these through four test strings and printed Y for a match:

/^\d{5}$/                   "02139":Y "2139":-  "021390":- "0213a":-
/^\d{5}(-\d{4})?$/          "02139":Y "02139-4307":Y "02139-43":- "02139-":-
/^#[0-9a-f]{6}$/i           "#1a2b3c":Y "#1A2B3C":Y "#abc":- "#12345g":-
/^#(?:[0-9a-f]{3}){1,2}$/i  "#abc":Y "#aabbcc":Y "#abcd":- "#abcde":-

The second line is a real format: five digits, then an optional dash-and-four-digits group. 02139-43 fails because the group only works in full. The last line goes one step further and accepts either three or six hex digits by repeating a group of three, one or two times: #abc and #aabbcc pass, and #abcd and #abcde don’t.

Ranges are greedy

A range with a top and a bottom takes as much as it can:

"12345 6".match(/\d{2,4}/g)         // [ '1234' ]
"a aa aaa aaaa".match(/\ba{2,}\b/g) // [ 'aa', 'aaa', 'aaaa' ]

In the first line \d{2,4} grabbed four digits from 12345. The leftover 5 and the lone 6 are too short for the minimum of two. Without anchors, a counted pattern will happily match a piece of something longer, so ^\d{5}$ and not \d{5} is the pattern for “exactly five”. The second line uses a {n,} minimum with word boundaries to pick out runs of two or more.

One item at a time

As with the other quantifiers, the count belongs to the one item before it. To repeat a sequence, wrap the sequence in a group:

"ababab".match(/(ab){2}/)[0]        // "abab"
"ababab".match(/(?:ab){2,}/)[0]     // "ababab"
"abc".match(/a{0}/)[0]              // ""

ab{2} would mean a then bb. The third line shows that {0} is legal and matches the empty string, which is rarely useful. Reversed bounds are an error, caught when the pattern is built: a{3,2} gave numbers out of order in {} quantifier in JavaScript, and min repeat greater than max repeat at position 2 in Python.

Braces that aren’t quantifiers

Curly braces are the least consistent part of regex across flavours. Here is the missing-lower-bound form, {,3}, in six engines on this machine:

Python 3.9   re.findall(r"a{,3}", "aaaa")        ['aaa', 'a', '']     quantifier
Perl 5.34    "aaaa" =~ /a{,3}/g                  aaa|a                quantifier
pcre2grep    echo aaaa | pcre2grep -o 'a{,3}'    aaa, a               quantifier
JavaScript   /a{,3}/.test("aa")                  false                literal text "a{,3}"
JavaScript   /a{,3}/.exec("a{,3}")[0]            "a{,3}"
macOS grep   echo aaaa | grep -oE 'a{,3}'        no match, exit 1     literal text

In Python, Perl and PCRE it means “zero to three”. In JavaScript and macOS’s grep -E it is literal text. The portable spelling is {0,3}. And a { that does not form a valid count is treated as literal text in JavaScript’s default mode: /a{2/.exec("a{2") matched a{2. With the u flag it is an error, Incomplete quantifier. And a count with nothing before it, like /{2}/, fails with Nothing to repeat. If you mean a literal brace, escape it as \{, so /\{\d+\}/.exec("hello {42}") returned {42}. Python also read a{2 as literal text.

In POSIX basic syntax the braces are the other way round, as the flavors lesson showed: grep 'a\{2\}' is the quantifier and grep 'a{2}' is literal text. I ran both on a file with aa and a{2}, and grep -E 'a{2}' printed aa, while BRE a{2} printed a{2}. A last real-world use is an IPv4 shape: ([0-9]{1,3}\.){3}[0-9]{1,3} found 192.168.1.20. It also accepted 999.999.999.999 when I tried it, so a count alone does not check the value of each octet. The later validation lessons come back to that.

About the video

Kris Jordan’s “Regular Expression “Repeats” Operator finds Repetitions (formally: Quantifier/Closure operators)” was published on 22 May 2020 and runs 10 minutes 28 seconds. The description says it teaches the quantifier with a range from a lower to an upper bound and its syntax. Its chapters are Introduction to repeats, Understanding quantifiers, Using basic repeats, Advanced pattern matching, Recap and best practices and Closing and next steps. The embed stops at 9:28, before the closing teaser for a puzzle. It uses VS Code’s search box and puzzle files, per the description, so the flavour is whatever VS Code uses, which I did not check. I couldn’t read a transcript, so I can’t say whether it covers {n,}, literal braces or the flavour differences above. English per its title and description.

What I did not run

VS Code’s find box, GNU grep, regex101, and the {,3} form in Java, Go and Ruby.

Next

Ranges and * and + are greedy: they take as much as they can. What that does to a pattern, and how to turn it off, is the next lesson: Greedy and lazy quantifiers.

Check yourself

  1. 01How do you match a US ZIP code of five digits, optionally followed by a dash and four digits?

    /^\d{5}(-\d{4})?$/. The group with ? makes the +4 part optional, and the anchors reject anything extra. It accepted 02139 and 02139-4307 and rejected 02139-43.

  2. 02What does /\d{2,4}/g find in '12345 6'?

    Only '1234'. The range is greedy and takes up to four digits, then the leftover 5 is a single digit and 6 is too, so neither reaches the minimum of two.

  3. 03Why is /a{,3}/ a trap?

    In JavaScript and macOS grep -E it matches the literal text a{,3}, while in Python 3.9 it means zero to three a's. Write /a{0,3}/ to mean the same everywhere.

  4. 04Which of (ab){2} and ab{2} matches 'abab'?

    (ab){2}. The count binds to the group, giving abab. ab{2} means a followed by two b's, which is abb.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark