An Introduction to Programming

Python for All

Chapter Ten — Exercises

Thanasis Troboukis  ·  All Chapters

Chapter Ten

Exercises

Ten practical exercises to build confidence with regular expressions.

01

Find the first 4-digit year in the text.

Hint: use re.search() with a pattern like \d{4}.

Python · Your solution
02

Extract all numbers from the text as a list.

Hint: use re.findall() with \d+.

Python · Your solution
03

Replace all years with the word YEAR.

Hint: use re.sub().

Python · Your solution
04

Check if a code matches exactly two uppercase letters, dash, four digits.

Hint: use re.fullmatch() with r"[A-Z]{2}-\d{4}".

Python · Your solution
05

Find words that start with capital A.

Hint: use an anchor and word characters.

Python · Your solution
06

Extract whole-word cat matches only (not scatter or bobcat).

Hint: use word boundaries \b.

Python · Your solution
07

Extract all emails from the text.

Hint: start from \w+@\w+\.\w+.

Python · Your solution
08

Use capturing groups to extract year, month, and day from a date.

Hint: pattern like (\d{4})-(\d{2})-(\d{2}).

Python · Your solution
09

Show the difference between greedy and lazy matching on HTML tags.

Hint: compare <.*> and <.*?>.

Python · Your solution
10

Mini challenge: validate Greek phone numbers in format 210-123-4567 from a list and print only valid ones.

Hint: use re.fullmatch() in a loop.

Python · Your solution

Chapter Navigation

Move between chapters.

Loading Python environment — this may take a moment…