Python Glossary Русский

all Python 3reterm

Groups in patterns

groups

The extended group constructs: named groups, non-capturing groups, lookahead and lookbehind.

Syntax

(?P<name>...) именованная
(?:...) не захватывающая
(?=...) lookahead
(?!...) negative lookahead
(?<=...) lookbehind

Capturing parentheses change what findall returns: with one group it hands back that group's text instead of the whole match, so use (?:...) when the parentheses exist only to attach a repetition. Lookarounds are zero-width — they test the neighbouring text without consuming it, and it never shows up in the result. In re a lookbehind must be fixed width, so (?<=ab|cde) will not compile at all.

Examples

import re
re.search(r'(?P<d>\d+)', 'x42').group('d') # → '42'
re.findall(r'(?:\d+)', '1 2') # → ['1', '2'] без захвата
re.findall(r'\d+(?= руб)', '5 руб 3 кг') # → ['5']
re.findall(r'\d+(?! руб)', '5 руб 3 кг') # → ['3']
re.findall(r'(?<=@)\w+', 'user@host') # → ['host']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy