all Python 3reterm
re
module
Regular expressions: searching, extracting and replacing text by pattern.
Syntax
import re
Write patterns as raw strings r'...', otherwise \b and \d turn into control characters or warnings. match looks only at the start of the string, search looks anywhere, and fullmatch needs the whole string to match; on failure they return None rather than raising. For a simple substring check, in and str.startswith are enough and a regular expression is overkill.
Examples
import re
text = 'order 12, items 7'
print(re.findall(r'\d+', text)) # → ['12', '7']
print(re.match(r'\d+', text)) # → None — match ищет с начала
print(re.search(r'\d+', text).group()) # → 12
print(re.sub(r'\d+', '#', text)) # → order #, items #
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy