← Python from Scratch Lesson 56 of 78 · 10 XP

Regular expressions

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A regular expression is a pattern for finding text. For example, "a plus, a seven and 10 digits" is the pattern of a phone number.

The main pattern elements:

Pattern Means
\d any digit
\w a letter, a digit or _
\s a whitespace character
. any character
+ one or more times
* zero or more times
{3} exactly 3 times
[abc] one of the characters
\+ the + character itself (special characters are escaped with \)

Functions of the re module:

import re

re.findall(r"\d+", "in 2024 there are 12 months")  # ['2024', '12']
re.search(r"\d+", "abc 42 x")                  # finds the first match
re.sub(r"\s+", " ", "lots    of spaces")       # 'lots of spaces'
re.fullmatch(r"\d{4}", "2024")                 # does the whole string fit?

The letter r before a string makes it "raw": \d doesn't turn into a string escape. Always write r"..." for regular expressions.

Task. Write a function find_phones(text) that returns a list of all phone numbers of the form +7 followed by exactly 10 digits (for example, +77011234567), in the order they appear.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.