Python Glossary Русский

all Python 3reterm

Pattern special characters

patterns

The special characters of regular expressions: metacharacters, character classes, quantifiers and anchors.

Syntax

. ^ $ * + ? {n,m} [] | () \ \d \w \s

Always write patterns as raw strings: without the r prefix Python processes the backslashes itself, so \b turns into a backspace character before re ever sees it. Inside square brackets most metacharacters go literal — a dot or a plus is just that character — while ^ at the start negates the class and a hyphen between two characters means a range. Quantifiers are greedy by default: .* stretches to the last possible match, and .*? is the lazy form.

Examples

import re
re.findall(r'.', 'ab') # → ['a', 'b']  . любой символ
re.findall(r'\d+', 'x12y3') # → ['12', '3']  \d цифры
re.findall(r'\w+', 'hi_2!') # → ['hi_2']  \w буквы/цифры/_
re.findall(r'a{2,3}', 'a aa aaa') # → ['aa', 'aaa']
re.findall(r'cat|dog', 'cat and dog') # → ['cat', 'dog']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy