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})/gCaptures year (group 1), month (group 2), and day (group 3) from an ISO date
/(cat|dog)/gMatches and captures either 'cat' or 'dog'
Exercise
Write a pattern with a capturing group that matches a time like "12:30" or "9:45" (digits, colon, digits).
Your pattern: