Python

Regex in Python with re: search, fullmatch, findall and sub

Python’s standard `re` module covers the most common Regex tasks. Raw strings such as `r"\d+"` are a useful habit because they reduce escaping conflicts.

Before you start: test every pattern with examples that should match and examples that should fail.

Compile or use functions directly

For a pattern you reuse, re.compile() makes the intent explicit. For one-off checks, calling re.search() directly is fine.

import re
pattern = re.compile(r'\d{3}')
print(bool(pattern.search('order 123')))

search, match, and fullmatch

search() looks anywhere in the string, match() starts at the beginning, and fullmatch() requires the entire string to match. For format validation, fullmatch() is often a clean option.

findall for extraction

findall() returns all occurrences and works well for codes, numbers, and simple tokens.

re.findall(r'\b\d{3}\b', '123 42 999')
# ['123', '999']

sub for replacement

re.sub() applies Regex-based text transformations and can be used for cleanup, masking, and normalization.

Watch captured groups in findall

With capturing groups, findall() may return group contents instead of the full match. Use a non-capturing group (?:...) when grouping is structural only.

Next step: test it for real

Use the Playground to experiment with the pattern, then practice in the game with feedback on false positives and false negatives.

Practice in the gameTest in Playground

Keep learning

← Back to learning hub