Home / Learn / Code for makers

Regular expressions for beginners

New to this? Read from the top. Already know the basics? Jump to Going deeper for intermediate and advanced detail.

A regular expression highlighting every voltage value in a line of text
Beginner

A regular expression, or regex, is a small pattern that describes text. Regex can find every email address in a document, check that a postcode looks right, or reformat thousands of dates at once. The syntax looks cryptic at first, but it's built from a handful of simple pieces.

Practise each example in the regex tester as you read.

Literal characters

Most characters simply match themselves. The pattern cat finds "cat" in "concatenate". Regex is case-sensitive unless you turn on the ignore-case flag.

Character classes

PatternMatches
.Any single character except a new line
\dA digit, 0 to 9
\wA "word" character: a letter, digit or underscore
\sWhitespace: a space, tab or new line
[aeiou]Any one of the characters listed
[A-Z]Any character in the range A to Z
[^0-9]Any character except a digit

To match a special character like . or ? literally, put a backslash before it: \.

Quantifiers: how many

PatternMeans
*0 or more
+1 or more
?0 or 1 (optional)
{3}Exactly 3
{2,4}Between 2 and 4

So \d+ matches a whole number like 2026, and colou?r matches both "color" and "colour".

Anchors and groups

  • ^ matches the start of the text and $ the end. ^\d+$ means "only digits, nothing else".
  • \b marks a word boundary, so \bcat\b finds "cat" but not the "cat" inside "concatenate".
  • Parentheses ( ) make a group, which you can reuse or pull out separately.
  • | means "or": red|green matches either.

Regex in Python

Python's built-in re module handles regex. Write patterns as raw strings, r"...", so the backslashes reach the regex unchanged.

import re

text = "Order 1042 shipped 2026-11-18. Questions? Email help@example.com or sales@example.co.uk"

print(re.findall(r"\d+", text))
# ['1042', '2026', '11', '18']

print(re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text))
# ['help@example.com', 'sales@example.co.uk']

# Reformat dates from YYYY-MM-DD to DD/MM/YYYY using groups
print(re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", text))
# Order 1042 shipped 18/11/2026. Questions? Email help@example.com or sales@example.co.uk

# Check a whole string matches
print(bool(re.fullmatch(r"\d{4}", "2026")), bool(re.fullmatch(r"\d{4}", "20266")))
# True False

The email pattern is deliberately simple. Real email addresses can be surprisingly complicated, so for important checks, send a confirmation email rather than relying on a pattern.

Common pitfalls

  • Greedy matching. .* grabs as much as it can. In <b>one</b> and <b>two</b>, the pattern <b>.*</b> matches the whole line. Add ? to make it lazy: <b>.*?</b> matches each one separately.
  • Forgetting to escape. . matches any character, so example.com also matches "exampleXcom". Use example\.com.
  • Slow patterns. Nested quantifiers like (a+)+ can take an extremely long time on some inputs. Our tester stops a pattern after a second if this happens.
  • Using regex for everything. For HTML, JSON or CSV, use a proper parser instead. See JSON for beginners.
Intermediate and advanced

Going deeper

Groups you can name, and groups that don't capture

import re

m = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", "Shipped 2026-11-18")
print(m.group("day"), m.groupdict())

# (?:...) groups without capturing: useful with | and quantifiers
print(re.findall(r"(?:Mr|Ms|Dr)\.? (\w+)", "Dr Patel met Ms. Jones and Mr Smith"))
18 {'year': '2026', 'month': '11', 'day': '18'}
['Patel', 'Jones', 'Smith']

Python names groups with (?P<name>...). JavaScript uses (?<name>...).

Lookaheads and lookbehinds

These check what's around a match without including it:

  • (?=...) means "followed by", and (?!...) means "not followed by".
  • (?<=...) means "preceded by", and (?<!...) means "not preceded by".
print(re.findall(r"(?<=£)\d+(?:\.\d{2})?", "Kit £24.99, cable £3, case $15"))

# Password check: 8+ chars with at least one digit and one capital
for pw in ["sunshine1", "Sunshine1", "Sun1"]:
    print(pw, bool(re.fullmatch(r"(?=.*\d)(?=.*[A-Z]).{8,}", pw)))
['24.99', '3']
sunshine1 False
Sunshine1 True
Sun1 False

Flags and readable patterns

re.IGNORECASE ignores case, re.MULTILINE makes ^ and $ match at every line, and re.DOTALL lets . match new lines. re.VERBOSE allows spaces and comments inside a pattern, which makes complex ones far easier to maintain:

uk_postcode = re.compile(r"""
    ^[A-Z]{1,2}\d[A-Z\d]?   # outward code, e.g. SW1A
    \s?                     # optional space
    \d[A-Z]{2}$             # inward code, e.g. 1AA
""", re.VERBOSE | re.IGNORECASE)

print([bool(uk_postcode.match(p)) for p in ["SW1A 1AA", "m1 1ae", "12345"]])
[True, True, False]

This checks the general shape of a UK postcode. It can't tell whether a postcode actually exists.

Catastrophic backtracking

Most regex engines, including Python's and JavaScript's, try alternatives by backtracking. Patterns with nested or overlapping quantifiers, such as (a+)+$ or (\w+\s?)+$, can try an exponential number of combinations on input that almost matches, freezing a program or server. Avoid nesting quantifiers over the same characters, make alternatives mutually exclusive, and limit input length. Precompiling with re.compile helps performance when a pattern is reused, but doesn't prevent backtracking.

Sources

The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.