Capturing groups and numbering

Beginner · 14 min

A capturing group saves the text its parentheses matched. Learn the numbering rule, group 0, reading groups in JavaScript and Python, and unmatched vs empty.

Before thisGrouping with parentheses

The Coding Train · 14 min

Capturing groups and numbering

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

Taught by The Coding TrainReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Matching tells you whether and where. Capturing tells you which part: each pair of parentheses saves the text it matched, in a numbered slot.
  • Groups are numbered by the position of their opening parenthesis, counting from the left, starting at 1. Group 0 is the whole match, and nesting does not change the rule.
  • In JavaScript, exec and match return an array: m[0] is the whole match, m[1] the first group, plus m.index. In Python it is m.group(0), m.group(1) and m.groups().
  • A group that took no part in the match is undefined in JavaScript and None in Python. A group that matched the empty string is an empty string. Those are different values.
  • A group inside a repetition holds only its last pass: /(\w)+/ on abc captures c, not a, b and c.

Matching vs. getting the pieces

Suppose a log line says released 2026-11-23 today and you want the year, the month and the day as three separate values. A plain match gets you the whole date, 2026-11-23. You’d then have to split that string yourself, and now you are writing a second parser to undo the first one.

A capturing group fixes this. When you wrap part of a pattern in parentheses, the engine does the grouping job from the last lesson and also writes down the text that group matched. Think of the pattern as a form with labelled boxes. Each pair of parentheses is a box, and after the match the engine hands you the form back with the boxes filled in.

The numbering rule

Boxes are numbered by where their opening parenthesis sits, counting from the left, starting at 1. Box 0 is special: it is the whole match, parentheses or not.

const m = /(\d{4})-(\d{2})-(\d{2})/.exec('released 2026-11-23 today');
m[0]  // '2026-11-23'
m[1]  // '2026'
m[2]  // '11'
m[3]  // '23'
m.index  // 9

The result is an array with a few extra properties. m.index is where the match started in the input, and here that was position 9. Destructuring skips the whole-match slot neatly: const [, y, mo, d] = m gave { y: '2026', mo: '11', d: '23' }.

Nesting doesn’t change the rule. I ran /((a)(b(c)))/ on abc and got:

["abc","abc","a","bc","c"]

Slot 0 is the whole match, slot 1 is the outermost group (abc), slot 2 is (a), slot 3 is (b(c)) which holds bc, and slot 4 is the (c) nested inside it. To find any group’s number, count opening parentheses from the left until you reach it.

Reading groups in Python

Python spells the same idea with methods on the match object:

>>> m = re.search(r'(\d{4})-(\d{2})-(\d{2})', 'released 2026-11-23 today')
>>> m.group(0), m.group(1), m.group(3)
('2026-11-23', '2026', '23')
>>> m.groups()
('2026', '11', '23')
>>> m.span(2)
(14, 16)

groups() leaves out group 0, which is why it has three items here, not four. m.group(1, 3) returned ('2026', '23'), and asking for a group that doesn’t exist, m.group(4), raised IndexError: no such group. In JavaScript the same mistake just gives undefined.

Unmatched is not the same as empty

Two cases look alike and aren’t. In /(a)|(b)/ on the input b, the first alternative never ran, so group 1 never took part:

[ 'b', undefined, 'b', index: 0, ... ]

Group 1 is undefined. Compare /(a*)b/ on b. The group did run and matched zero characters, so you get an empty string:

[ 'b', '', index: 0, ... ]

Python draws the same line with None versus '': re.search(r'(a)|(b)', 'b').groups() printed (None, 'b'), and re.search(r'(a*)b', 'b').groups() printed ('',). A trap worth knowing: JSON.stringify turns the undefined slot into null, so printing through JSON can hide the difference. Python lets you pick a stand-in with groups('-'), which printed ('-', 'b').

This matters for optional parts. /^(\w+)(?::(\d+))?$/ on localhost gave m[2] === undefined. Code that does Number(m[2]) on that would get NaN. Check for the undefined first.

A group in a loop remembers only the last pass

/(\w)+/ on abc gave ["abc","c"]. The group is re-entered on each repetition and overwrites its slot, so only the final pass is left. If you need every repetition, match the single-character pattern repeatedly instead, which splitting and extracting covers. Also, no match returns null in JavaScript and None in Python, so guard before indexing.

About the video

The embedded video is The Coding Train’s “2.4: Regular Expressions: Capturing Groups - Programming with Text”, published 17 September 2016 and 13 minutes 41 seconds long. Its chapters are Intro, Capturing Groups, Matching Groups, Replacing Groups and Matching Links. The description says it covers capturing parentheses and numbered groups used in find and replace. It is part of an NYU course series and uses JavaScript. I couldn’t read a transcript, so I can’t say how it treats nested numbering, unmatched groups or the Python spelling. Those are covered above from my own runs. English per its title and description.

What I did not run

The exact code in the video, and how engines other than V8 and Python’s re treat a group inside a repetition.

Next

Sometimes you want the grouping and not the numbered slot. Non-capturing groups shows how to keep the parentheses without paying for the capture.

Check yourself

  1. 01In /((a)(b(c)))/ matched against abc, which text does each group number hold?

    Group 1 holds abc, group 2 holds a, group 3 holds bc and group 4 holds c. Numbering follows the opening parentheses from left to right, so the outer group is 1 and its children follow in order.

  2. 02What is the difference between a group that is undefined and a group that is an empty string?

    Undefined means the group never took part in the match, for example the unused side of an alternation. An empty string means it took part and matched zero characters, as /(a*)b/ does on the input b. Python uses None and an empty string for the same two cases.

  3. 03What does /(\w)+/ capture on the string abc?

    The string c. The group is re-entered on every repetition and each pass overwrites the slot, so only the last one survives. To keep all of them you need a different approach, such as matchAll over a single-character pattern.

  4. 04How do you pull the year, month and day out of 2026-11-23 into three variables in JavaScript?

    Run /(\d{4})-(\d{2})-(\d{2})/.exec(text), then destructure while skipping the whole-match slot: const [, year, month, day] = match. Check for null first, because exec returns null when nothing matches.

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