Python Glossary Русский

all Python 3refunction

re.search()

search

Finds the first match of the pattern anywhere in the string. Returns a Match or None.

Syntax

re.search(pattern, string, flags=0)

The classic bug is calling .group() straight on the result: with no match you get None and an AttributeError instead of a clear message, so check the result first (a walrus operator inside an if reads well here). search() stops at the first hit — when you need every occurrence, use findall() or finditer().

Examples

import re
m = re.search(r'\d+', 'abc123def') # → <Match '123'>
m.group() # → '123'
m.start() # → 3
re.search(r'cat', 'the cat sat') # → <Match 'cat'>
re.search(r'dog', 'the cat sat') # → None

See also

Open in the full glossarydocs.python.orgReport an inaccuracy