Python Glossary Русский

all Python 3refunction

re.match()

search

Checks whether the pattern matches at the start of the string. Returns a Match object or None.

Syntax

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

The name misleads: match() does not test the string against the pattern, it only tries the pattern at position 0, so a match in the middle is invisible to it — that is search()'s job. It says nothing about the end of the string either, so use fullmatch() for validation; MULTILINE does not help, since it changes what ^ means, not where match() starts looking.

Examples

import re
m = re.match(r'\d+', '123abc') # → <Match '123'>
m.group() # → '123'
re.match(r'\d+', 'abc123') # → None
m2 = re.match(r'[a-z]+', 'hello world') # → <Match 'hello'>
m2.end() # → 5

See also

Open in the full glossarydocs.python.orgReport an inaccuracy