Python RegEx
Python · Working with Data
Theory
A regular expression (regex) is a mini-language for describing text patterns, and Python's re module applies them. \d means a digit, \w a word character, \s whitespace, . any character; + means one or more, * zero or more, {3} exactly three; [A-Z] is a character class and ( ) creates a capture group. Writing patterns as raw strings, r'\d+', stops Python from treating backslashes as escapes.
The main functions: re.search() finds the first match anywhere and returns a match object (or None); re.match() only checks the start of the string; re.findall() returns every match as a list; re.sub() replaces matches. re.findall(r'\d+', 'Order 123, Item 45') returns ['123', '45'] - note they are strings, so convert with int() if needed.
Why we use it
Text data is messy: phone numbers, order IDs, emails and codes hide inside free text. Regex extracts, validates or cleans them in one line where manual string slicing would take many.
When to use it
Use regex for pattern-based tasks such as extracting numbers, validating formats or cleaning text. For simple fixed checks, string methods like startswith(), split() or 'in' are clearer and faster.
How it works
- Write a pattern, e.g. r'\d+'
- Scan the text from left to right
- Does the text here match? Yes: Record it and continue after it. No: Move one character forward.
- Repeat until the end of the text
- findall returns ['123', '45']
Syntax
import re
re.match(pattern, text)Example
re.findall(r'\d+', 'Order 123, Item 45')
# ['123', '45']Key points
- findall() returns all matches
- search() finds the first match anywhere in a string
- match() only checks the beginning of the string
- Use raw strings r'...' for patterns
- Matches are strings - convert with int() for numbers