Groups and capture
Parentheses (...) group part of a pattern - and also capture what
matched there, so you can pull it back out. str.match(/Hello, (\w+)!/)
returns an array where [0] is the whole match and [1] is whatever the
first group captured.
Naming a group makes this easier to read: (?<year>\d{4}) captures the same
thing but stores it under match.groups.year instead of a numbered index.
This is how you turn "did it match" into "here's the piece I actually wanted."
Your task: write capturedName(str), returning the name captured from a
greeting shaped like "Hello, Ada!" (or null if it doesn't match), and
parseDate(dateStr), returning { year, month, day } (each a string) parsed
from a date shaped like "2026-07-10" using named groups (or null if it
doesn't match).
You'll practice:
Capturing part of a match with (...) and reading it from the match array
Naming a group with (?<name>...) and reading match.groups.name
Show a hint
Show solution
Related reading: Using Regex for Real (and the Gotchas) →
Previous Next