CKTIS / Python
re.Pattern.search: Find the first match with a compiled pattern
Use a compiled regular expression to find the first match in a string or within a range set by start and end indexes.
Version: Python 3.12
Syntax
pattern = re.compile(expression, flags=0)
pattern.search(string[, pos[, endpos]]) -> re.Match | Nonere.Pattern.search is a method of the object returned by re.compile(). The call pattern.search(string) returns a re.Match for the first position where the pattern matches, even in the middle of the string. By contrast, pattern.match() tries only at the starting position, and pattern.fullmatch() requires the whole specified range to match.
The optional pos is the index to start searching at and defaults to 0. The optional endpos is the exclusive upper limit and defaults to the string's length. In CPython 3.12, both pos and endpos are clamped to the range from 0 through the string's length, inclusive. If endpos < pos after clamping, the method returns None. Setting pos is not the same as slicing: the ^ anchor does not treat pos as a new beginning of the string.
Check match is not None before reading the result. A zero-length match is still a re.Match. Use match.group(0) to get the entire matched substring and match.span() to get its (start, end) indexes in the original string, with the end index excluded.
The module-level function re.search(pattern, string, flags=0) takes the pattern as an argument and has no pos or endpos parameters. The method uses the pattern already stored on the compiled object, which you can reuse. Pass flags as arguments to re.compile(), not to pattern.search().
Examples
import re
pattern = re.compile(r"[A-Z][0-9]{2}")
text = "IDs: A17, B42"
for match in (pattern.search(text), pattern.search(text, pos=8)):
if match is not None:
print(match.group(0), match.span())
print(pattern.search(text, pos=8, endpos=12))Result
A17 (5, 8) B42 (10, 13) None
The pattern matches one uppercase ASCII letter followed by two ASCII digits. The first call finds `A17`; starting at `pos=8` skips it and finds `B42`. With `endpos=12`, the final `2` is outside the search range, so the result is `None`.
Related lessons
- Python · Lesson 30 · Intermediate · Version: 3