Learn Python
>>> advanced_python.regex

Regular Expressions in Python

#concept

A regular expression (regex) is a compact pattern language for matching, searching, and manipulating text based on its shape rather than an exact literal string — matching "any digit," "one or more letters," or an email-like pattern, for instance. Python's built-in re module provides the tools to apply these patterns against actual text.

#how it works
1

import re

Brings in the module, part of the standard library.

2

re.search(pattern, text)

Looks for the pattern anywhere in text, returning a match object if found, or None if not.

3

re.findall(pattern, text)

Returns every non-overlapping match as a list of strings.

4

re.sub(pattern, replacement, text)

Replaces every match with replacement, returning the resulting new string.

5

Special characters build the pattern language

A digit placeholder, a "one or more" quantifier, and parentheses to capture part of a match.

#example
import re
 
text = "Call me at 123-456-7890 or 987-654-3210"
 
match = re.search(r"\d{3}-\d{3}-\d{4}", text)
print(match.group())
 
all_numbers = re.findall(r"\d{3}-\d{3}-\d{4}", text)
print(all_numbers)
 
masked = re.sub(r"\d{3}-\d{3}-\d{4}", "[phone number]", text)
print(masked)
Output
123-456-7890
['123-456-7890', '987-654-3210']
Call me at [phone number] or [phone number]
1The pattern matches exactly three digits, a hyphen, three more digits, another hyphen, then four digits — the shape of a US phone number.
2re.search finds the first match anywhere in the text and match.group() retrieves the actual matched text.
3re.findall returns every match in the whole string as a list, catching both phone numbers.
4re.sub replaces every match with a placeholder, producing a new string with both numbers masked out.
#use cases
Validating input formats, like checking an email address or phone number roughly matches the expected shape
Extracting specific pieces of information from unstructured text, like all URLs or dates in a document
Search-and-replace operations more powerful than plain string methods, like masking sensitive data
Parsing simple structured text formats, like log files, where the same pattern repeats predictably

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.