Skip to content
dreamcode
dreamcode
Map
Regex
Lesson 55 of 77
+15 XP on finish
PYTHON ADVANCEDChapter 9 · Python Advanced

Regular expressions

A regular expression is a pattern for matching text. The re module searches with it: re.findall(pattern, text) returns every match, re.search finds the first one, and re.sub replaces matches. Common pieces: \d is a digit, \w a word character, + means one or more, * zero or more, [aeiou] any one of these letters, and ( ) captures part of a match. Write patterns as raw strings, r"...", so backslashes stay as typed.

Worked example

How it reads

  • \d+ means one or more digits in a row
  • The parentheses in (\d+) capture a part you can read with group(1)
  • re.sub replaces every match with new text
Common mistakes
  • Forgetting the r prefix: in a normal string, "\b" is a backspace character, not a word boundary.
Cloud tip: Regex is powerful but easy to misread. For simple jobs like splitting on commas, plain string methods are clearer.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Use re.findall to pull out the numbers, convert them to ints and print their total: 49.

Press Run to check your work.