Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

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")))
Output
['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

PatternMatches
\d \w \sa 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"))
Output
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"))
Output
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

  1. Find all the words that start with a capital letter in a sentence.
  2. Check with fullmatch whether a string is a 6-digit Indian PIN code.
  3. Take all the hashtags such as #python out of a message.
  4. Replace every number in a text with the same number in square brackets.