Lesson 42 of 55
10 mins readPython Lookarounds, Word Boundaries & Anchors
In Plain English
Zero-width assertions match positions without consuming characters: anchors (`^`, `$`, `\b`, `\A`, `\z`), lookaheads (`(?=...)`, `(?!...)`), and lookbehinds (`(?<=...)`, `(?<!...)`).
Deep Dive: How It Works
String Anchors: `\A` (beginning of string), `\z` (absolute end of string).
Word Boundary (\b): Matches transition between word `\w` and non-word characters.
Positive Lookahead (?=...): Matches only if followed by the subpattern.
Positive Lookbehind (?<=...): Matches only if preceded by the subpattern.
Core Rules to Remember

Zero-Width Assertions: Validate surrounding context without including it in the match.

Precise Word Boundaries: `\bcat\b` matches "cat" but ignores "caterpillar" or "bobcat".
Live Interactive Example
Hit Run Code to see it liveExtracting Prices with Lookbehind
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: Lookbehind extracted 49.99 without the dollar sign, and \b matched the exact word "cat".
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Match Exact Keyword with Word Boundaries
Set `my $str = "perl scripting in perl5";`
Extract all exact occurrences of word `\bperl\b` into `my @matches = ($str =~ /\bperl\b/g);`
Print `"Matches: " . scalar(@matches) . "\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.