re.search
The one you usually want: tries every position from left to right and stops at the first match. Also available as Pattern.search(string, pos, endpos) on a compiled pattern.
Demo
import re re.search('\\d+', 'order 66, then 3')
span=(start, end) is a half-open range: text[start:end] is the match. An empty match is still a match — x* finds zero x at position 0, so search returns a Match (truthy) with span=(0, 0). In the pos tab, ^\d+ fails at pos 3 because ^ only matches at the true beginning of the string; pos past the end is clamped to the end.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| pattern | str | re.Pattern | yes | The regular expression — write it as a raw string, r'...'. |
| string | str | yes | The text to scan. |
| flags | re.RegexFlag | int | no (0) | re.IGNORECASE, re.MULTILINE, … combined with |. Not allowed when pattern is already compiled. |
Return value
re.Match | None — The first match (leftmost position), or None when the pattern matches nowhere.
Common patterns
import re if m := re.search(r'(\d+) items?', line): count = int(m.group(1))
import re has_digit = re.search(r'\d', password) is not None
import re ERR = re.compile(r'\bERROR\b') errors = [ln for ln in log_lines if ERR.search(ln)]
Examples
Pitfalls
import re re.search(r'\d*', 'abc 42')
import re re.search(r'\d+', 'abc 42')
import re pat = re.compile(r'abc') re.search(pat, 'ABC', re.I)
import re pat = re.compile(r'abc', re.I) pat.search('ABC')
When to use
- Finding whether and where a pattern occurs anywhere in a string
- Extracting the first occurrence with its groups
- Must match at the start → re.match; the whole string → re.fullmatch
- Need every occurrence → re.findall or re.finditer
- Fixed text → the in operator or str.find
Notes
FAQ
A re.Match object for the first match, or None. The Match gives the text (m.group()), its position (m.start(), m.end(), m.span()) and the groups. Its repr looks like <re.Match object; span=(6, 8), match='66'>.