Basic Matching
import re m = re.search(r"\d+", "abc 42 def") print(m.group()) # 42
Finding All
re.findall(r"\d+", "a1 b22 c333") # ['1', '22', '333']
Replacing
re.sub(r"\s+", " ", "hello world") # 'hello world'
Useful Character Classes
\ddigit,\Dnon-digit\wword char,\Wnon-word\swhitespace,\Snon-whitespace.any char (except newline)
Quantifiers
*zero or more,+one or more?zero or one,{n,m}n to m times
Groups
m = re.match(r"(\d{4})-(\d{2})-(\d{2})", "2026-04-22")
year, month, day = m.groups()
Regex rarely appears on HKDSE Paper 1, but it is invaluable for real-world text processing.
Practise this on PyForm โ free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm โ