Labs ICT
โญ Pro Login

Regex

match() and search()

re.match() checks the start of a string. re.search() looks anywhere. Both return a match object or None.

import re

text = "Hello, my email is user@example.com"
m = re.search(r"\w+@\w+\.\w+", text)
if m:
    print("Found:", m.group())
Try it Yourself โ†’

findall()

re.findall() returns a list of all non-overlapping matches. Each match is a string (or a tuple if there are groups).

import re

text = "Apples cost 3, bananas 2, cherries 5"
nums = re.findall(r"\d+", text)
print(nums)
Try it Yourself โ†’

sub() and split()

re.sub() replaces matches with a string. re.split() splits the string at each match. Both are very handy for text cleanup.

import re

text = "one1two2three3four"
parts = re.split(r"\d", text)
print(parts)

cleaned = re.sub(r"\d", "-", text)
print(cleaned)
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which module provides regex support in Python?