Skip to chapter content
navan✳THE BUILD LABPYTHON / GUIDE
0/26 read
CHAPTER 09 / 26 · DATA AND TEXT

Finding patterns in text.

Use regular expressions for precise text shapes, with boundaries and tests.

BY NAVAN SAMI5 MIN READTHEORY FIRST
01 / THE BASICS

Start here.

A regular expression describes a shape of text rather than one literal word. Python's re module supplies functions and compiled pattern objects for using it. In the example, the raw string r'^[A-Z]{2}-\d{3}$' means an entire string with two uppercase ASCII letters, a hyphen, and three digits. The r prefix tells Python to leave backslashes for the regex parser. The backslash before d means a digit in regex syntax, not the literal letter d.

Read the pattern from left to right. ^ marks the start, [A-Z] means one uppercase ASCII letter, {2} repeats that piece twice, the hyphen matches itself, \d means one digit, {3} repeats it three times, and $ marks the end. re.fullmatch asks whether the whole input obeys the rule. re.search would accept a matching piece anywhere inside a longer string, which is useful for discovery but wrong when the entire field must be a code.

A match object contains information about what matched; no match is represented by None. Check that a match exists before asking it for group(). Parentheses can capture one part of a pattern, and a named group gives that part a readable name. A pattern can describe format without understanding meaning: a date-like string may match digits and separators yet be an impossible calendar date. Use a date parser for that semantic question.

02 / THE IDEA

Build the model.

A regular expression describes a pattern of characters rather than one exact string. It is useful when a document contains many candidates with the same shape: an invoice reference, a date-like label, or a repeated marker. Python's re module compiles or searches such patterns and returns match objects that describe where and what was found.

Start with the smallest rule that describes your data. Literal letters match themselves; character classes such as [A-Z] describe one choice; quantifiers such as {3} repeat the preceding item; parentheses group a part you want to extract. Anchors ^ and $ keep a validation pattern attached to the beginning and end of the whole string.

03 / UNDER THE SURFACE

How it works.

Use a raw string, prefixed with r, for most patterns. It keeps a backslash intended for the regex engine from being interpreted first by Python's string parser. re.search finds a match anywhere, re.fullmatch requires the entire string to satisfy the pattern, and re.findall gathers matches. Choose the operation by the question you are asking, not just by the easiest method name.

A match object is either present or None. Check for None before calling group(). Named groups make an extraction readable: (?P<area>...) names the portion rather than forcing the next reader to remember group 1. When a pattern grows complicated, split it into smaller checks or use a real parser for formats with nesting and quoting.

Regex is a tool for structure, not meaning. A pattern can confirm that a value looks like YYYY-MM-DD while still accepting an impossible date. Parse a date with datetime after the shape check if calendar validity matters. Likewise, do not assume one pattern can define every legitimate email address.

04 / A WORKED EXAMPLE

Read it line by line.

example.py
import re
pattern = re.compile(r'^[A-Z]{2}-\d{3}$')
for code in ['AB-123', 'A-123', 'AB-12X']:
    print(code, bool(pattern.fullmatch(code)))

The pattern asks for two uppercase ASCII letters, a hyphen, and three digits from start to end. AB-123 matches and prints True. A-123 has only one letter; AB-12X ends with a letter instead of a digit, so both print False. fullmatch states that extra characters before or after the code are unacceptable.

05 / ANOTHER EXAMPLE

See the rule again.

example-2.py
import re
line = 'Ticket: 407'
match = re.fullmatch(r'Ticket: (?P<number>\d{3})', line)
if match:
    print(match.group('number'))

The output is 407 as text. The named group identifies the part you want after matching the whole line. Convert with int() only if you need arithmetic; preserving it as text keeps leading zeroes.

06 / REMEMBER THIS

A mistake to avoid.

If you use re.search for validation, 'prefix AB-123 suffix' could pass because the valid-looking fragment appears inside a longer invalid value. Use fullmatch for a whole-field contract.

Finished this chapter?
Built with curiosity. By Navan Sami. ↗Python · Understand the idea, then write the code.