Regular Expressions

Python 3.14 · ✓ verified by execution on 2026-07-28

Regular Expressions

Regular expressions (regex) are powerful tools for searching, extracting, and replacing text patterns. Python’s built-in re module provides operations similar to those found in Perl, making it easy to harness the power of regular expressions.

Key Fact: The re module provides regular expression matching operations similar to those found in Perl.

Using Raw Strings for Regex Patterns

Regular expressions often use the backslash character (\) to indicate special forms or to allow special characters to be used without invoking their special meaning. However, standard Python string literals consume backslashes (e.g. \n), so you must use raw strings (r"...") to pass backslashes directly to the regex engine.

python
import re

text = 'This is a backslash: \\'
# r'\\' means a raw string with two backslashes. The regex engine sees \\ and matches a literal \
match = re.search(r'\\', text)
print('Found backslash!' if match else 'Not found')
Output
Found backslash!

A common pitfall is misunderstanding the difference between re.match() and re.search().

Click to view match vs search visualizer
python · visualize
import re

text = 'Hello World'

# match looks at the start
match1 = re.match(r'Hello', text)
print('Match Hello:', match1.group() if match1 else 'No match')

# search finds it anywhere
match2 = re.search(r'World', text)
print('Search World:', match2.group() if match2 else 'No match')

Extracting Multiple Matches

The re.findall() function returns all non-overlapping matches of a pattern in a string. If the pattern has no capture groups, it returns a list of strings.

python
import re

matches = re.findall(r'\d+', 'There are 3 apples and 15 oranges.')
print(matches)
Output
['3', '15']

Capture Groups

You can use parentheses () to create capture groups, allowing you to extract specific parts of a match. If the pattern has multiple capture groups, re.findall() returns a list of tuples containing the captured strings. For a single match object, you can access groups using .group().

python
import re

match = re.search(r'(\w+)@(\w+\.\w+)', 'Email: [email protected]')
if match:
    print(match.group(1))
    print(match.group(2))
Output
user
example.com

Substituting Text

The re.sub() function returns the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in the string by a replacement string.

python
import re

text = 'I like cats. Cats are great.'
result = re.sub(r'[Cc]ats', 'dogs', text)
print(result)
Output
I like dogs. dogs are great.

Check yourself

What is the difference between re.match() and re.search()?

Reveal answer

re.match() only looks at the very beginning of the string, while re.search() looks anywhere in the string. — re.match() only looks at the very beginning of the string, while re.search() checks anywhere.

Why should you use raw strings (e.g., r'...') for regular expression patterns in Python?

Reveal answer

Because standard string literals consume backslashes, so raw strings pass backslashes directly to the regex engine. — Standard string literals consume backslashes (e.g. \n), so you must use raw strings to pass them to the engine.

What does re.findall() return if the pattern contains multiple capture groups?

Reveal answer

It returns a list of tuples containing the captured strings. — If the pattern has multiple capture groups, re.findall() returns a list of tuples containing the captured strings.

Challenges

Challenge 1 +20 XP

Use re.findall() to extract all phone numbers in the format XXX-XXX-XXXX from the given text.

python
  • Test 1 — expects "['123-456-7890', '987-654-3210']\n"
Show solution (0 XP)
import re

def get_phones(text):
    return re.findall(r'\d{3}-\d{3}-\d{4}', text)

print(get_phones('Call 123-456-7890 or 987-654-3210.'))

Challenge 2 +20 XP

Use re.sub() to mask all vowels in the string with an asterisk (*).

python
  • Test 1 — expects "R*g*l*r *xpr*ss**ns *r* p*w*rf*l.\n"
Show solution (0 XP)
import re

def mask_vowels(text):
    return re.sub(r'[aeiouAEIOU]', '*', text)

print(mask_vowels('Regular Expressions are powerful.'))