Python Glossary Русский

all Python 3reterm

re flags

flags

The flags change how a pattern behaves: case sensitivity, multi-line mode, whether the dot matches \n, and verbose syntax.

Syntax

re.IGNORECASE (re.I), re.MULTILINE (re.M), re.DOTALL (re.S), re.VERBOSE (re.X)

The flags do not overlap: re.M only changes what ^ and $ mean, and it takes re.S to make the dot match a newline. The other trap is argument position — re.sub() takes count and re.split() takes maxsplit before flags, so a flag passed without its keyword lands in the counter (since 3.13 such a positional call also emits DeprecationWarning), and on a compiled pattern the flags are already baked in, so p.match(s, re.I) reads re.I as a starting offset.

Examples

import re
re.findall(r'hello', 'Hello HELLO', re.I) # → ['Hello', 'HELLO']
re.findall(r'^\d', '1\n2\n3', re.M) # → ['1', '2', '3']
re.match(r'.+', 'a\nb', re.S).group() # → 'a\nb'
pat = re.compile(r'''
\d+   # цифры
[a-z] # буква
''', re.X)
pat.findall('1a 2b 3') # → ['1a', '2b']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy