re
Regular expressions: searching, checking, and replacing fragments of text according to a pattern.
- Returns
search()andfullmatch()return aMatchorNone,findall()a list, andsub()a new string.
Example
#import re
text = "Submit tasks 1_4 and 1_12 by 2026-10-05, and task 2_1 by 2026-10-12."
print(re.findall(r"\d+_\d+", text))
match = re.search(r"(\d{4})-(\d{2})-(\d{2})", text)
print(match.group(), match.group(2))
print(re.sub(r"\s+", " ", "Too many spaces"))Definition and usage
#The re module handles regular expressions, meaning patterns that describe text. \d stands for a digit, \s for a whitespace character, \w for a letter, digit, or underscore, [A-Z] for an uppercase letter from the given range, and + for repeating the previous element at least once. From such building blocks you can assemble a pattern for a date, a task number, or an email address.
The most important functions are re.search() (the first match anywhere in the text), re.fullmatch() (whether the whole text matches the pattern), re.findall() (a list of all matches), re.sub() (replacement), and re.split() (splitting). search() and fullmatch() return a Match object, or None when nothing matches.
Write patterns as raw strings with the r prefix, e.g. r"\d+", so that Python does not interpret backslashes its own way. Parentheses create groups whose contents you read with the group() method. A pattern you use many times can be compiled with re.compile().
Syntax
#import re
re.search(pattern, string, flags=0)
re.fullmatch(pattern, string)
re.findall(pattern, string)
re.sub(pattern, repl, string)
re.split(pattern, string)Parameters
#pattern
str
The regular expression pattern, preferably as a raw stringr"...".string
str
The text being searched.repl
str or function
Inre.sub(): the text inserted in place of the match, or a function that computes it.flags
optional
Modifiers, e.g.re.IGNORECASE(ignoring letter case).
More examples
#import re
pattern = re.compile(r"(?P<user>[\w.]+)@(?P<domain>[\w-]+\.\w+)")
for email in ["emma.smith@codeworlds.pl", "jack@", "mia@school.edu"]:
match = pattern.fullmatch(email)
print(email, "->", match["domain"] if match else "invalid")import re
text = "Python, HTML;CSS python"
print(re.split(r"[,;\s]+", text))
print(re.findall(r"python", text, flags=re.IGNORECASE))
prices = "HTML 49 PLN, Python 79 PLN"
print(re.sub(r"\d+", lambda m: str(int(m.group()) * 2), prices))Good practices
#- Always use raw strings
r"..."for patterns. Without them,"\b"means the backspace character, not a word boundary. - When a pattern contains groups,
findall()returns the contents of the groups instead of the whole matches. Write a group you do not want returned as(?:...). - Before you call
group(), check that the result ofsearch()is notNone. Otherwise you get anAttributeError.
Related entries
#- str.replace()Returns a string with occurrences of a given fragment replaced.
- str.split()Splits a string into a list of parts using a separator.
- str.find()Returns the index of the first occurrence of a fragment, or -1.
- str.isdigit()Checks whether a string consists only of digits.
- str.startswith()Checks whether a string starts with a given fragment.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.