Edexcel International Advanced Level Computer Science, point 18.1.2
A regular expression (regex) is a pattern that describes a set of strings. Python's re module uses them to find text and to validate data. Check the Programming Language Subset (PLS) for the functions allowed.
import re
Pattern syntax
| Pattern | Matches | Example |
|---|---|---|
| A letter or digit | That exact character | cat matches cat |
. |
Any one character (except newline) | c.t matches cat, cot |
\d |
A digit (0 to 9) | \d\d matches 42 |
\w |
A letter, digit or underscore | \w+ matches hello_1 |
\s |
White space (space, tab, newline) | a\sb matches a b |
[abc] |
One of the listed characters | [aeiou] matches a vowel |
[a-z] |
One character in a range | [A-Z] matches a capital |
[^abc] |
Any character NOT listed | [^0-9] matches a non-digit |
* |
Zero or more of the previous | ab* matches a, abbb |
+ |
One or more | \d+ matches 7, 2026 |
? |
Zero or one (optional) | colou?r matches color, colour |
{n} |
Exactly | \d{4} matches 2026 |
{n,m} |
Between and | \d{1,3} matches 7, 123 |
^ |
Start of the string | ^Hi |
$ |
End of the string | end$ |
| |
Either / or | cat|dog |
( ) |
A group (to repeat, or to capture) | (ab)+ matches abab |
\. |
A literal dot (escape special characters with \) |
\.com |
Use a raw string (r"...") so that backslashes are kept as they are: r"\d+".
a. Finding
re.search: the first match anywhere
text = "Call 0161 496 0123 or 020 7946 0958"
m = re.search(r"\d{3,4}", text)
print(m.group(), m.start(), m.end()) # 0161 5 9
print(re.search(r"xyz", text)) # None: no match
re.search returns a match object or None, so check before using it.
re.findall: every match, as a list
print(re.findall(r"\d+", text))
# ['0161', '496', '0123', '020', '7946', '0958']
words = "The rain in Spain stays mainly in the plain"
# ['rain', 'Spain', 'mainly', 'plain']
print(re.findall(r"\w*ain\w*", words))
re.finditer: matches with positions
for m in re.finditer(r"[A-Z]\w+", words): # capitalised words
print(m.group(), m.start()) # The 0, then Spain 12
re.sub: find and replace
print(re.sub(r"\d", "#", "Pin 4821")) # Pin ####
print(re.sub(r"\s+", " ", "too many spaces")) # too many spaces
re.split: split at a pattern
print(re.split(r"[,;]\s*", "a, b;c, d")) # ['a', 'b', 'c', 'd']
Groups: capturing parts of a match
m = re.search(r"(\d{2})/(\d{2})/(\d{4})", "Born on 15/11/2008.")
# 15/11/2008 (the whole match)
print(m.group(0))
print(m.groups()) # ('15', '11', '2008')
day, month, year = m.groups()
b. Validating
Validation checks that the whole input fits a pattern. Use re.fullmatch (the entire string must match), or ^...$ with re.match.
def valid(pattern, text):
return re.fullmatch(pattern, text) is not None
Examples
A simple UK-style postcode (not every real case):
POSTCODE = r"[A-Z]{1,2}\d[A-Z\d]? \d[A-Z]{2}"
print(valid(POSTCODE, "SW1A 1AA")) # True
print(valid(POSTCODE, "M1 1AE")) # True
print(valid(POSTCODE, "1234 ABC")) # False
A phone number (11 digits starting 0):
PHONE = r"0\d{10}"
print(valid(PHONE, "01614960123")) # True
print(valid(PHONE, "1614960123")) # False
A date DD/MM/YYYY (format only; it doesn't check the date exists):
DATE = r"\d{2}/\d{2}/\d{4}"
print(valid(DATE, "15/11/2026")) # True
print(valid(DATE, "5/11/2026")) # False
A simple email address:
EMAIL = r"[\w.]+@[\w]+\.[a-z]{2,}"
print(valid(EMAIL, "amy.lee@example.com")) # True
print(valid(EMAIL, "amy@@example")) # False
A strong-ish password (at least 8 characters, a digit and a capital):
def strong(p):
return (len(p) >= 8 and re.search(r"\d", p) is not None
and re.search(r"[A-Z]", p) is not None)
print(strong("Passw0rdX"), strong("password")) # True False
Search or full match?
| Function | Succeeds when |
|---|---|
re.search |
The pattern appears anywhere in the string |
re.match |
The pattern matches at the start |
re.fullmatch |
The whole string matches (best for validation) |
Limits of regular expressions
- A regex checks format, not meaning:
99/99/9999matches the date pattern but isn't a real date. Combine with other checks. - Complex patterns are hard to read, so comment them and test them.
- They can't handle nested structures (such as matching brackets) or real email rules perfectly.
- Poorly written patterns can be slow on some inputs.
Worked example
Task: read lines of a log like 2026-11-15 ERROR disk full and extract the date and message of every ERROR line.
log = """2026-11-14 INFO started
2026-11-15 ERROR disk full
2026-11-15 WARN low memory
2026-11-16 ERROR network down"""
pattern = r"(\d{4}-\d{2}-\d{2}) ERROR (.+)"
errors = re.findall(pattern, log)
print(errors)
# [('2026-11-15', 'disk full'), ('2026-11-16', 'network down')]
How the pattern works: (\d{4}-\d{2}-\d{2}) captures a date (4 digits, a hyphen, 2 digits, a hyphen, 2 digits), then a space and ERROR, then (.+) captures the rest of the line. findall with two groups returns a list of tuples.
Exam tip: write patterns as raw strings. For validation, use re.fullmatch so the whole input must fit. Check that search didn't return None before using .group(). Know the common symbols (\d, \w, +, *, ?, {n}, [ ], ^, $) and say what a given pattern matches.
Check yourself
What does the pattern \d{4} match?
Exactly four digits in a row.
What is the difference between re.search and re.fullmatch?
search finds the pattern anywhere in the string; fullmatch succeeds only if the whole string matches.
What does re.findall(r"\d+", "a1b22c333") return?
['1', '22', '333'].
Why use a raw string for a regular expression?
So that backslashes are passed to the re module unchanged instead of being treated as Python escape characters.
Give a limitation of using a regex for validation
It checks only the format, not the meaning; for example 99/99/9999 matches a date pattern but isn't a real date.