Skip to main content
Regexflux
Lesson 6 of 120 completed

Capturing Groups

Use parentheses to group patterns and capture matched text for later use.· 8 min

Concept

Parentheses (...) serve two purposes:

1. **Grouping**: Apply quantifiers to a sequence, e.g., (ab)+ matches "ababab" 2. **Capturing**: The matched text is captured and can be referenced as $1, $2, etc. in replacement strings, or accessed programmatically

Groups are numbered left-to-right by their opening parenthesis. The first ( is group 1, the second is group 2, and so on.

You can also use alternation | inside a group: (cat|dog) matches either "cat" or "dog".

/(\d{4})-(\d{2})-(\d{2})/g

Captures year (group 1), month (group 2), and day (group 3) from an ISO date

Date: 2024-03-17
Born on 1999-12-31
2024/03/17
24-3-7
/(cat|dog)/g

Matches and captures either 'cat' or 'dog'

I have a cat
my dog is friendly
fish tank
catdog show

Exercise

Write a pattern with a capturing group that matches a time like "12:30" or "9:45" (digits, colon, digits).

Your pattern:

Must match

Meeting at 12:30
wakes at 9:45 AM
Time: 10:00
it is 8:05 now

Must not match

12-30
twelve thirty
noon
1230