Programming languages · Intermediate · 25 min
Write regular expressions you can read and test
By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15.2 · pytest 9.2
You will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
On this page
Bank alerts, mobile-money confirmations and delivery texts all carry the same few facts: when, how much, and who. A regular expression (regex) is a small pattern language for finding text with a known shape, and it is the right tool for pulling those facts out of a line like Ksh500 sent to WANJIRU 0722 000 111 on 15.11.2026.
Regexes earn their bad name when they are written as one unreadable line and never tested. In this tutorial you do the opposite. You write the tests first, build three patterns in small named pieces, check each against real-looking messages, and watch a badly written pattern hang so you can recognise the shape and avoid it. You use Python's built-in re module, and the last step shows the same patterns in JavaScript, with a list of the syntax that differs.
The sample messages use Nigerian and Kenyan formats: naira (NGN, ₦) and shilling (KES, KSh) amounts, +234 and +254 numbers, and day-first dates. The techniques carry over to any country's formats.
Step 1 · Create the project and the sample messages
Make a project folder, add pytest as a development dependency, and tell pytest to import code from the project folder:
mkdir -p ~/regex-demo
cd ~/regex-demo
uv init --no-package
uv add --dev "pytest>=9.2,<9.3"
cat >> pyproject.toml <<'TOML'
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
TOMLSave four messages to practise on. They are invented, but they mix the formats you meet in real alerts: thousands separators, three date styles, a one-time password that must not be mistaken for anything, and numbers written with and without spaces.
cat > messages.txt <<'TXT'
14/11/2026 10:42 You sent NGN 12,500.00 to ADA OBI 0803 123 4567. Fee NGN 50. Ref: TXN84Q2.
QK7PL2 Confirmed. Ksh500 sent to WANJIRU 0722 000 111 on 15.11.2026. New balance KES 1,250.50.
Your OTP is 448812. Do not share it.
Received ₦3,000 from +2349051234567 on 16-11-2026. Bal: NGN 5,000.00
TXTCheck it worked
uv run pytest --version
wc -l messages.txtThe first line shows pytest 9.2.0 or a later 9.2 release, and wc reports 4 messages.txt.
Step 2 · Write the tests before the patterns
A regex is code, and a short one can hide a lot of behaviour. Writing the cases down first forces you to decide what should match and, just as important, what should not: a one-time password is not a phone number, and 31/02/2026 is not a date.
Create one test file per pattern, so each can pass on its own while you build the module:
mkdir -p tests
cat > tests/test_dates.py <<'PY'
from datetime import date
import pytest
from sms_patterns import find_dates
@pytest.mark.parametrize(
("text", "expected"),
[
("Paid on 14/11/2026 at 10:42", [date(2026, 11, 14)]),
("Due 3.2.2026", [date(2026, 2, 3)]),
("05-11-2026 and 06/11/2026", [date(2026, 11, 5), date(2026, 11, 6)]),
("14/11-2026", []), # mixed separators
("14/13/2026", []), # there is no month 13
("31/02/2026", []), # the right shape, but not a real day
("Ref 2026-11-14", []), # year-first is a different format
("Your OTP is 448812", []),
],
)
def test_find_dates(text, expected):
assert find_dates(text) == expected
PY
cat > tests/test_amounts.py <<'PY'
import time
from decimal import Decimal
import pytest
from sms_patterns import find_amounts
@pytest.mark.parametrize(
("text", "expected"),
[
("You sent NGN 12,500.00 to Ada", [("NGN", Decimal("12500.00"))]),
("Received ₦3,000 from Tunde", [("NGN", Decimal("3000"))]),
(
"Ksh500 paid. New balance KES 1,250.50.",
[("KES", Decimal("500")), ("KES", Decimal("1250.50"))],
),
("Fee NGN 50, balance ngn 2,000", [("NGN", Decimal("50")), ("NGN", Decimal("2000"))]),
("NGN 1,2345", []), # broken thousands grouping
("It makes 500 people happy", []), # "kes" inside a word
],
)
def test_find_amounts(text, expected):
assert find_amounts(text) == expected
def test_amounts_stay_fast_on_hostile_input():
text = "NGN " + "1," * 50_000
started = time.perf_counter()
find_amounts(text)
assert time.perf_counter() - started < 1
PY
cat > tests/test_phones.py <<'PY'
import pytest
from sms_patterns import find_phones, is_phone
@pytest.mark.parametrize(
("text", "expected"),
[
("Call 0803 123 4567 now", ["+2348031234567"]),
("From +2349051234567:", ["+2349051234567"]),
("Sent to 0712 345 678", ["+254712345678"]),
("Agent +254 110-123-456", ["+254110123456"]),
("Ada 0803 123 4567, Wanjiru 0722 000 111", ["+2348031234567", "+254722000111"]),
("Acct 123408031234567", []), # inside a longer number
("Your OTP is 448812", []),
],
)
def test_find_phones(text, expected):
assert find_phones(text) == expected
@pytest.mark.parametrize(
("value", "expected"),
[
("0803 123 4567", True),
("+254712345678", True),
("call 0803 123 4567", False),
("0803 123 45678", False),
("0803 123 4567\n", False),
],
)
def test_is_phone(value, expected):
assert is_phone(value) is expected
PYEach phone number is returned in one normalised form, + followed by the country code and the digits, so the rest of a program never has to think about spaces or a leading 0.
Run the tests. They fail, because the module does not exist yet:
uv run pytest -qCheck it worked
The output reports ModuleNotFoundError: No module named 'sms_patterns' for each of the three files and ends with a line like Interrupted: 3 errors during collection. A failing first run is the point: it proves the tests really run your code.
Step 3 · Match dates with character classes and named groups
Create sms_patterns.py with the date pattern. It is built from short raw strings, one idea per line. Python joins strings that sit next to each other, so this is still one pattern:
cat > sms_patterns.py <<'PY'
"""Patterns for pulling dates, amounts and phone numbers out of SMS text."""
import re
from datetime import date
from decimal import Decimal
DATE = re.compile(
r"\b"
r"(?P<day>0?[1-9]|[12][0-9]|3[01])"
r"(?P<sep>[/.-])"
r"(?P<month>0?[1-9]|1[0-2])"
r"(?P=sep)"
r"(?P<year>20[0-9]{2})"
r"\b"
)
def find_dates(text):
found = []
for m in DATE.finditer(text):
try:
found.append(date(int(m["year"]), int(m["month"]), int(m["day"])))
except ValueError:
pass # the right shape, but not a real day, such as 31/02
return found
PYRead it piece by piece:
[12]is a character class: one character from the set.[0-9]is a range.[/.-]is a slash, a dot or a hyphen; inside a class the dot means a literal dot, and a hyphen at the end is literal too.?makes the item before it optional, and{2}means exactly two.0?[1-9]accepts3and03.|is alternation: one choice or another.0?[1-9]|[12][0-9]|3[01]covers days 1 to 31 without accepting 32 or 40. The group around it keeps the choices from leaking into the rest of the pattern.(?P<day>...)is a named group, so the code readsm["day"]instead of counting brackets.(?P=sep)is a backreference: it must match exactly what thesepgroup matched. That rejects14/11-2026, which mixes separators.\bis an anchor. It matches no characters, only a word boundary, so the pattern cannot start or end in the middle of a longer run of digits.
The DATE pattern uses [0-9] rather than \d on purpose. In Python, \d in a text pattern matches any Unicode decimal digit, including Arabic-Indic digits such as ٣. That is useful when users type in Arabic script, but surprising when you expect only 0 to 9, so write what you mean.
finditer walks every match in the text. The date() call does the job a regex cannot: 31/02/2026 has a perfectly valid shape, and only a calendar knows February has no 31st. Let the regex check shape and let ordinary code check meaning.
Check it worked
uv run pytest -q tests/test_dates.pyThe output ends with 8 passed.
Step 4 · Match amounts with alternation and lookarounds
Amounts need three new tools: an alternation of currency spellings, a flag to ignore case, and lookarounds, which check what comes before or after a match without consuming it. Append the pattern to the module:
cat >> sms_patterns.py <<'PY'
AMOUNT = re.compile(
r"(?<![A-Za-z])" # not the tail end of a longer word
r"(?P<currency>NGN|KES|KSh|₦)\s?"
r"(?P<value>[0-9]{1,3}(?:,[0-9]{3})+|[0-9]+)"
r"(?P<cents>\.[0-9]{2})?"
r"(?![0-9]|[.,][0-9])", # not cut off in the middle of a number
re.IGNORECASE,
)
CURRENCIES = {"ngn": "NGN", "₦": "NGN", "kes": "KES", "ksh": "KES"}
def find_amounts(text):
return [
(
CURRENCIES[m["currency"].lower()],
Decimal(m["value"].replace(",", "") + (m["cents"] or "")),
)
for m in AMOUNT.finditer(text)
]
PYWhat each new piece does:
re.IGNORECASEacceptsngn,KshandKSHwithout listing every spelling.(?<![A-Za-z])is a negative lookbehind: the match must not be preceded by a letter. Without it, thekesinmakes 500would read as Kenyan shillings.(?:...)is a group that does not capture. Use it when you need brackets for+or|but do not need the text.[0-9]{1,3}(?:,[0-9]{3})+|[0-9]+accepts either correctly grouped thousands (12,500) or plain digits (500). The grouped form comes first, because alternation tries choices from left to right and keeps the first that leads to a full match.(?![0-9]|[.,][0-9])is a negative lookahead: the next characters must not be a digit, or a comma or dot followed by a digit. That rejectsNGN 1,2345instead of quietly returning1, whileNGN 50,at the end of a clause still matches.Decimal, notfloat, holds money, so1250.50stays exactly1250.50.
Quantifiers such as * and + are greedy: they take as much as they can, then give characters back only if the rest of the pattern fails. Adding ? after them makes them lazy, taking as little as possible. See the difference on a reference code:
cat > greedy.py <<'PY'
import re
sms = "Ref: QK7PL2. Bal: KES 1,250.50."
print("greedy:", re.search(r"Ref: (.*)\.", sms)[1])
print("lazy: ", re.search(r"Ref: (.*?)\.", sms)[1])
print("class: ", re.search(r"Ref: ([^.]*)\.", sms)[1])
PY
uv run greedy.pyThe greedy .* runs to the end of the line and backs up to the last dot, swallowing the balance. The lazy .*? stops at the first dot. The third form, [^.]* (any character except a dot), says the same thing as the lazy version more precisely and is usually the better choice.
Check it worked
greedy.py prints greedy: QK7PL2. Bal: KES 1,250.50, then lazy: QK7PL2 and class: QK7PL2. Then run the amount tests:
uv run pytest -q tests/test_amounts.pyThe output ends with 7 passed.
Step 5 · Match phone numbers in verbose mode, and validate with fullmatch
Phone numbers have the most variation, so this pattern uses verbose mode. With re.VERBOSE, spaces and line breaks in the pattern are ignored and # starts a comment, which lets you lay a regex out like code. Spaces inside a character class still count, so [ -] keeps meaning "a space or a hyphen". Append it:
cat >> sms_patterns.py <<'PY'
PHONE = re.compile(
r"""
(?<![0-9+]) # not in the middle of a longer number
(?:
(?:\+234[ ]?|0) # Nigeria: country code or leading 0
(?P<ng>
[789][01][0-9] # network prefix such as 803, 905, 701
[ -]?[0-9]{3}
[ -]?[0-9]{4}
)
|
(?:\+254[ ]?|0) # Kenya: country code or leading 0
(?P<ke>
[17][0-9]{2} # mobile prefix such as 712, 110
[ -]?[0-9]{3}
[ -]?[0-9]{3}
)
)
(?![0-9]) # and no digit straight after
""",
re.VERBOSE | re.ASCII,
)
SEPARATORS = re.compile(r"[ -]")
def find_phones(text):
found = []
for m in PHONE.finditer(text):
if m["ng"]:
found.append("+234" + SEPARATORS.sub("", m["ng"]))
else:
found.append("+254" + SEPARATORS.sub("", m["ke"]))
return found
def is_phone(value):
return PHONE.fullmatch(value) is not None
PYA Nigerian mobile number has ten digits after the 0 or +234; a Kenyan one has nine after the 0 or +254. The lookbehind and lookahead stop the pattern from finding a number inside a longer string of digits, such as an account number. The prefixes are deliberately loose: they cover the 070, 080, 081, 090 and 091 ranges in Nigeria and the 07 and 01 ranges in Kenya, without a list of carriers that goes out of date. re.ASCII keeps every class and \b to plain ASCII in this pattern.
re.compile runs once, when the module is imported, and the compiled patterns are reused by every call. Python's re also caches recently used patterns behind functions such as re.search, so compiling is not mainly about speed. It gives each pattern a name, keeps its flags beside it, and means a typo fails at import time rather than on the first message that reaches that code.
There are three ways to apply a pattern, and they answer different questions:
PHONE.search(text)finds the first match anywhere. Use it, orfinditer, to extract from free text.PHONE.match(text)only matches at the start, but may stop before the end.PHONE.fullmatch(text)must cover the whole string. Use it to validate one field, such as a phone number on a form.
is_phone uses fullmatch, so call 0803 123 4567 is rejected as a field value even though search finds a number inside it. A pattern ending in $ is not the same: in Python, $ also matches just before a trailing newline, so re.match(r"[0-9]+$", "123\n") succeeds while re.fullmatch(r"[0-9]+", "123\n") does not.
Check it worked
uv run pytest -q tests/test_phones.py
uv run pytest -qThe first run ends with 12 passed, and the full run with 27 passed.
Step 6 · Watch a bad pattern hang, then fix it
Some patterns take exponential time on inputs that almost match. The usual cause is a quantifier inside a quantified group where both can match the same characters, such as (\d+,?)+. On a string of 30 digits followed by an x, the engine tries every way of splitting the digits between the inner and outer + before it gives up. That is about a billion attempts. This is called catastrophic backtracking, and an attacker who can send text to your server can use it to tie up a worker.
Python's re module has no timeout option, so the script runs each match in a child process and stops it after two seconds:
cat > backtrack.py <<'PY'
import subprocess
import sys
import time
TEXT = "1" * 30 + "x"
PATTERNS = {
"bad ": r"^(\d+,?)+$",
"rewritten ": r"^\d{1,3}(?:,\d{3})*$",
"possessive": r"^(\d++,?)+$",
}
for label, pattern in PATTERNS.items():
code = f"import re; re.match({pattern!r}, {TEXT!r})"
started = time.perf_counter()
try:
subprocess.run([sys.executable, "-c", code], timeout=2, check=True)
print(label, "finished in", round(time.perf_counter() - started, 2), "s")
except subprocess.TimeoutExpired:
print(label, "still running after 2 s, stopped")
PY
uv run backtrack.py | tee backtrack.txtThere are two ways out. The rewritten pattern describes the shape exactly, one to three digits and then groups of a comma and three digits, so there is only one way to match any string. The possessive quantifier ++, available in Python since 3.11, never gives characters back once it has taken them, which removes the choices the engine would retry. The rewrite is usually clearer.
The amount test in your suite, test_amounts_stay_fast_on_hostile_input, is the guard for this: it feeds the pattern 100,000 characters of near-misses and fails if that takes more than a second. Add a test like it for any pattern that reads text from users. If you cannot avoid running patterns written by other people, run them in a separate process with a time limit, as this script does.
Check it worked
The output shows bad with still running after 2 s, stopped, and rewritten and possessive with finished in and a time well under a second.
Step 7 · Run the module on the messages, and know when to stop
Put the three finders together in a script that reads the sample file:
cat > extract.py <<'PY'
from pathlib import Path
from sms_patterns import find_amounts, find_dates, find_phones
lines = Path("messages.txt").read_text(encoding="utf-8").splitlines()
for number, line in enumerate(lines, start=1):
dates = [d.isoformat() for d in find_dates(line)]
amounts = [f"{currency} {value}" for currency, value in find_amounts(line)]
print(number, dates, amounts, find_phones(line))
PY
uv run extract.py | tee extract.txtThe one-time password on line 3 produces nothing, and each date style comes out in one ISO form. Passing encoding="utf-8" is still worth doing even though Python 3.15 defaults to UTF-8: it states what the file holds (the ₦ sign is not ASCII), and it keeps the script correct on Python 3.14 and earlier, where open() used the locale's encoding, which is often not UTF-8 on Windows.
A regex is the wrong tool in some common cases:
- HTML and XML nest, and a regex cannot track nesting reliably. Use a parser, such as Python's built-in
html.parseror a library like Beautiful Soup. - Email addresses: the full grammar is far larger than any pattern worth maintaining, and a valid-looking address may not exist. Check only that there is one
@with text on both sides and a dot in the domain, for examplere.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", value), then send a confirmation message. - Fixed formats with a library: dates in a known format (
datetime.strptime), URLs (urllib.parse), numbers (int,Decimal). A library already handles the edge cases. - When a pattern needs more than a screen of verbose mode, split the job into a few simple patterns plus ordinary Python, as
find_datesdoes with the calendar check.
Check it worked
The script prints four lines, like this:
1 ['2026-11-14'] ['NGN 12500.00', 'NGN 50'] ['+2348031234567']
2 ['2026-11-15'] ['KES 500', 'KES 1250.50'] ['+254722000111']
3 [] [] []
4 ['2026-11-16'] ['NGN 3000', 'NGN 5000.00'] ['+2349051234567']Step 8 · Port the patterns to JavaScript and PCRE
The same patterns often have to run in a browser form or another service. The core syntax (classes, quantifiers, groups, |, lookahead) is shared, but a few details differ. Python, JavaScript and PCRE2 (the library behind PHP's preg_ functions and many other tools) compare like this:
| Feature | Python | JavaScript | PCRE2 |
| --- | --- | --- | --- |
| Named group | (?P<name>...) | (?<name>...) | Accepts both forms |
| Named backreference | (?P=name) | \k<name> | Accepts both, and more |
| Verbose mode with comments | re.VERBOSE or (?x) | No such flag; build the pattern from commented strings | (?x) |
| Whole-string match | fullmatch | ^(?:...)$ with test() | ^(?:...)$, or \A...\z to rule out a trailing newline |
| \d | Any Unicode digit in text patterns, unless you pass re.ASCII | Only 0 to 9 | Only 0 to 9, unless Unicode properties mode (UCP) is on |
| Possessive ++ and atomic (?>...) | Python 3.11 and later | Not supported | Supported |
| Lookbehind | Fixed width only | Any length | Each alternative fixed length; bounded length in PCRE2 10.43 and later |
| All matches | finditer | matchAll, which needs the g flag | The host's match-all call, such as PHP preg_match_all |
Check the Python column yourself:
cat > compare.py <<'PY'
import re
for label, pattern in {
"(?P<year>...)": r"(?P<year>20[0-9]{2})",
"(?<year>...) ": r"(?<year>20[0-9]{2})",
"[0-9]++ ": r"[0-9]++",
}.items():
try:
re.compile(pattern)
print(label, "accepted")
except re.PatternError:
print(label, "rejected")
print(r"\d matches ٣:", bool(re.fullmatch(r"\d", "٣")))
print(r"\d matches ٣ with re.ASCII:", bool(re.fullmatch(r"\d", "٣", re.ASCII)))
print("$ accepts a trailing newline:", bool(re.match(r"[0-9]+$", "123\n")))
PY
uv run compare.py | tee compare.txtHere are the date and phone patterns in JavaScript. With no verbose mode, the phone pattern is assembled from named, commented parts with String.raw, so backslashes do not need doubling:
const DATE =
/\b(?<day>0?[1-9]|[12][0-9]|3[01])(?<sep>[\/.-])(?<month>0?[1-9]|1[0-2])\k<sep>(?<year>20[0-9]{2})\b/g;
for (const m of "Paid on 14/11/2026 at 10:42".matchAll(DATE)) {
console.log(m.groups.year, m.groups.month, m.groups.day);
}
// Nigeria: country code or leading 0, then ten digits
const ng = String.raw`(?:\+234 ?|0)(?<ng>[789][01][0-9][ -]?[0-9]{3}[ -]?[0-9]{4})`;
// Kenya: country code or leading 0, then nine digits
const ke = String.raw`(?:\+254 ?|0)(?<ke>[17][0-9]{2}[ -]?[0-9]{3}[ -]?[0-9]{3})`;
const body = String.raw`(?<![0-9+])(?:${ng}|${ke})(?![0-9])`;
const findPhones = new RegExp(body, "g");
const isPhone = (value) => new RegExp(`^(?:${body})$`).test(value);
console.log([..."Wanjiru 0722 000 111".matchAll(findPhones)].map((m) => m[0]));
console.log(isPhone("0803 123 4567"), isPhone("call 0803 123 4567"));Keep the g flag off a pattern you pass to test(). A global regex remembers where its last match ended in lastIndex, so calling test() twice on the same string can return true and then false. Port the tests too: the same list of cases, run with your JavaScript test runner, is what proves the two versions agree.
Check it worked
compare.py prints accepted for (?P<year>...) and [0-9]++, rejected for (?<year>...), then True, False and True for the last three lines. If you have Node.js, paste the JavaScript into node. It prints 2026 11 14, then [ '0722 000 111' ], then true false.
Step 9 · Clean up
The module and tests are yours to keep. Copy sms_patterns.py and the tests folder into your own project if they are useful. Then remove the demo folder; Python and uv stay installed:
cd ~
rm -rf ~/regex-demoCheck it worked
test ! -e ~/regex-demo && echo "removed"The command prints removed.
Next steps
- Clean text before you match it, with slicing,
split,stripand f-strings: work with text strings in Python. - Get more from the tests you wrote here, with fixtures and parametrize: test Python code with pytest.
- Learn what
encoding="utf-8"protects against and why two strings that look the same may not match: understand text encoding, UTF-8 and Unicode normalisation.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write generic functions and types in GoYou will replace three copies of a slice filter with one generic Go 1.27 function, then write constrained helpers, a custom constraint with ~, a generic Set type with an iterator and a generic method, and learn when the standard library or plain code is the better choice.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials