Labs ICT
๐ŸŽ“ SIWES/IT Login

Regex

1 min read | Python Tutorial
๐ŸŽ“

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

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())

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)

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)

๐Ÿงช Quick Quiz

Which module provides regex support in Python?