Regular Expressions: A Developer's Guide

The pattern language that scares everyone, demystified — anchors, classes, quantifiers, groups and lookaheads.

Regular expressions look like line noise until you learn the grammar — then they become the fastest way to validate, extract and transform text. This is the 80% that solves 95% of problems.

The building blocks

python
import re

# character classes and anchors
re.search(r"^hello", "hello world")     # ^ start
re.search(r"world$", "hello world")     # $ end
re.search(r"[0-9]+", "order 42")        # one or more digits
re.search(r"\d{3}-\d{4}", "call 555-0142")

Quantifiers

python
#  *  zero or more
#  +  one or more
#  ?  zero or one (optional)
#  {n} exactly n   {n,} at least n   {n,m} between n and m

re.fullmatch(r"colou?r", "color")   # matches "color" and "colour"
re.fullmatch(r"\d{4}", "2026")      # exactly four digits

Groups and capture

python
m = re.match(r"(\w+)@(\w+)\.com", "ada@lovelace.com")
print(m.group(1))   # ada
print(m.group(2))   # lovelace

# named groups read better
m = re.match(r"(?P<user>\w+)@(?P<domain>\w+)\.com", "ada@lovelace.com")
print(m.group("user"))

Lookahead — assert without consuming

python
# match "foo" only when followed by "bar"
re.search(r"foo(?=bar)", "foobar")    # matches
re.search(r"foo(?=bar)", "foobaz")    # no match

# negative lookahead — not followed by
re.search(r"\d+(?!\.)", "42.0")     # no match (42 is followed by .)

Common recipes

python
EMAIL    = r"[^@\s]+@[^@\s]+\.[^@\s]+"
PHONE    = r"\+?\d[\d -]{7,}\d"
URL      = r"https?://[\w.-]+/\S*"
DATE_ISO = r"\d{4}-\d{2}-\d{2}"

emails = re.findall(EMAIL, "contact ada@x.io or bob@y.com")
print(emails)   # ['ada@x.io', 'bob@y.com']
Test as you go, and prefer a few small patterns over one clever monster. Regex you can't read in six months is a liability, not an asset.

Regex is a tool like any other — intimidating at first, indispensable once it clicks.

Your move

Want us to build this for you?

We turn tutorials like these into production systems every day. Tell us what you need.

Start a project →