Lesson 38 of 55
9 mins readPython Character Classes, Shortcuts & Quantifiers
In Plain English
Character classes match categories of characters (`\d` for digits, `\w` for word characters, `\s` for whitespace). Quantifiers (`+`, `*`, `?`, `{min,max}`) control repetition counts.
Deep Dive: How It Works
Shortcuts: `\d` (digits [0-9]), `\w` (word [a-zA-Z0-9_]), `\s` (whitespace [ \t\r\n\f]).
Negated Shortcuts: `\D` (non-digit), `\W` (non-word), `\S` (non-space).
Quantifiers: `+` (1+), `*` (0+), `?` (0 or 1), `{n,m}` (n to m times).
Non-Greedy Modifiers: `+?` and `*?` match the minimum possible characters.
Core Rules to Remember

Built-in Character Classes: `\d`, `\w`, `\s` speed up common pattern recognition.

Greedy vs Lazy: Append `?` to make quantifiers non-greedy (lazy).
Live Interactive Example
Hit Run Code to see it liveValidating IP and Port Patterns
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Output Console
Click "Run Code" to view the rendered output.
How it works: \d+ captured the numeric port and <.+?> matched the opening tag non-greedily.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Extract User ID with \d+
Set `my $text = "Order id: 9874 completed";`
Use `if ($text =~ /id:\s+(\d+)/)` and print `"ID: $1\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.