Lesson 39 of 55
9 mins readPython Capturing Groups ($1, $2) & Named Captures
In Plain English
Parentheses `(...)` in regular expressions capture matching substrings into the special read-only variables `$1`, `$2`, `$3`. Modern Perl also supports named captures via `(?<name>...)` stored in `%+`.
Deep Dive: How It Works
Numbered Captures ($1, $2, ...): Left-to-right based on opening parenthesis order.
List Context Captures: `my ($day, $month, $year) = ($date =~ /(\d{2})-(\d{2})-(\d{4})/);`.
Non-Capturing Groups (?:...): Groups expressions for quantifiers without saving variables.
Named Captures: `(?<user>\w+)` accessible via `$+{"user"}`.
Core Rules to Remember

$1, $2 Capture Variables: Auto-populated with substrings matched inside `(...)`.

List Context Extraction: Directly unpack captures into variables in a single step.
Live Interactive Example
Hit Run Code to see it liveExtracting Date and Domain Information
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: Numbered captures unpacked date components and URL segments cleanly.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Capture Key-Value Pair
Set `my $config = "timeout=30";`
Extract key and value using `if ($config =~ /^(\w+)=(\d+)$/)` and print `"Key: $1, Val: $2\n"`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.