Python RegEx (Regular Expressions)
A regular expression, or regex, is a small pattern that describes text: "three digits", "a word that starts with a capital letter", "something that looks like an email address". Python's re module searches text for such patterns, takes out the parts that match, replaces them and splits text with them. String methods like find and replace handle fixed text; regular expressions handle patterns.
Finding matches
import re
text = "Order 12 apples, 7 mangoes and 150 grapes."
print(re.findall(r"\d+", text))
m = re.search(r"\d+", text)
print(m.group(), m.start())
print(re.search(r"kiwi", text))
print(bool(re.fullmatch(r"[A-Z]\w+", "Python")))['12', '7', '150'] 12 6 None True
findall returns every match as a list. search finds the first match and returns a match object, or None when there is none, so you can write if re.search(...):. fullmatch checks that the whole string fits the pattern, which is what you want for validating input. Write patterns as raw strings, r"...", so that backslashes reach the regex unchanged.
The pattern language
| Pattern | Matches |
|---|---|
\d \w \s | a digit, a word character (letter, digit or _), a space |
. | any character except a new line |
[aeiou] [a-z] | one of the listed characters, a range |
+ * ? | one or more, zero or more, zero or one of the item before |
{3} {2,4} | exactly 3, from 2 to 4 times |
^ $ | the start and the end of the text |
(...) | a group: a part you can take out |
Groups
Round brackets mark groups, the parts of a match you want to pull out:
import re
dates = "Exams on 2026-11-03 and 2026-12-15."
for year, month, day in re.findall(r"(\d{4})-(\d{2})-(\d{2})", dates):
print(f"{day}/{month}/{year}")
m = re.search(r"(?P<user>[\w.]+)@(?P<domain>[\w.]+)", "Write to asha.rao@example.com today")
print(m.group("user"), "at", m.group("domain"))03/11/2026 15/12/2026 asha.rao at example.com
With groups, findall returns a tuple of the groups for each match. (?P<name>...) gives a group a name.
Replacing and splitting
import re
print(re.sub(r"\s+", " ", "too many spaces"))
print(re.sub(r"\d", "#", "PIN 4821"))
print(re.split(r"[,;]\s*", "red, green;blue, yellow"))
print(re.sub(r"(\w+)@(\w+)", r"\2 / \1", "ravi@home"))too many spaces PIN #### ['red', 'green', 'blue', 'yellow'] home / ravi
In the replacement text of sub, \1 and \2 stand for the groups of the match.
Practice exercises
- Find all the words that start with a capital letter in a sentence.
- Check with
fullmatchwhether a string is a 6-digit Indian PIN code. - Take all the hashtags such as
#pythonout of a message. - Replace every number in a text with the same number in square brackets.