re

Regular expressions: searching, checking, and replacing fragments of text according to a pattern.

Returns
search() and fullmatch() return a Match or None, findall() a list, and sub() a new string.
On this page

Example

#
Python
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"))
Resultsaved result, you can check it
['1_4', '1_12', '2_1']
2026-10-05 10
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

#
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 string r"...".
  • string

    str

    The text being searched.
  • repl

    str or function

    In re.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

#
Validation and named groups
Python
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")
Resultsaved result, you can check it
emma.smith@codeworlds.pl -> codeworlds.pl
jack@ -> invalid
mia@school.edu -> school.edu
Splitting, flags, and replacing with a function
Python
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))
Resultsaved result, you can check it
['Python', 'HTML', 'CSS', 'python']
['Python', 'python']
HTML 98 PLN, Python 158 PLN

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 of search() is not None. Otherwise you get an AttributeError.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.