Пример 1. Поиск всех чисел
# regex_01_findall.py
import re
def extract_numbers(text: str) -> list[str]:
return re.findall(r"\d+", text)
if __name__ == "__main__":
sample = "Python 3.9, Java 17, C++ 14"
print(extract_numbers(sample)) # ['3', '9', '17', '14']
Пример 2. Почему важен r"..."
# regex_02_raw_string.py
import re
# С r: ищем цифры
print(re.findall(r"\d+", "Price: 123")) # ['123']
# Без r: Python превращает \d в обычную букву d
print(re.findall("\d+", "Price: 123")) # []
Пример 3. Классы символов
# regex_03_char_classes.py
import re
text = "\tPython 3.12, Java 17, C++ 14!\n"
print("Цифры:", re.findall(r"\d", text))
print("Двузначные:", re.findall(r"\d\d", text))
print("Буквы/цифры/_:", re.findall(r"\w", text))
print("Пробелы:", re.findall(r"\s", text))
print("Всё кроме \n:", re.findall(r".", text))
Пример 4. Квантификаторы
# regex_04_quantifiers.py
import re
text = """
Orders: ID123, ID4567, ID89
Numbers: 123-45-67, 321-45-67
Prices: 100$, 199.50$, 99.99€, 0.49€, .99€
Files: report.txt, report2.txt, report10.txt
"""
print("ID-коды:", re.findall(r"ID\d{2,}", text))
print("Телефоны:", re.findall(r"\d{3}-\d{2}-\d{2}", text))
print("Цены:", re.findall(r"\d+\.\d+", text))
print("Файлы:", re.findall(r"report\d*\.txt", text))
Пример 5. Жадные и ленивые квантификаторы
# regex_05_greedy_lazy.py
import re
text = "<div>Hello</div><div>World</div>"
greedy = re.findall(r"<.*>", text)
lazy = re.findall(r"<.*?>", text)
print("Жадно:", greedy)
print("Лениво:", lazy)
Пример 6. Якоря
# regex_06_anchors.py
import re
text = "Hello world! Welcome to world"
print(re.findall(r"^\w+", text)) # ['Hello']
print(re.findall(r"\w+$", text)) # ['world']
text2 = "category wildcat education _cat_ catalog"
print(re.findall(r"\bcat\w*", text2)) # ['cat', 'catalog']
Пример 7. re.search vs re.match
# regex_07_search_match.py
import re
text = "ID12345 is confirmed. ID23456 is confirmed"
match_search = re.search(r"ID\d+", text)
print("search:", match_search.group() if match_search else None) # ID12345
match_match = re.match(r"ID\d+", text)
print("match:", match_match.group() if match_match else None) # ID12345
# Тот же шаблон, но текст начинается не с ID
print(re.match(r"ID\d+", "Confirmed: ID12345")) # None
Пример 7a. re.finditer
# regex_07a_finditer.py
import re
text = "Order ID: 12345, Invoice No: 67890, Ref: ABC9876"
for match in re.finditer(r"\d+", text):
print(f"{match.group():>8} at {match.span()}")
Пример 8. Группы и негруппирующие скобки
# regex_08_groups.py
import re
text = "Order ID: 12345, Invoice No: 67890"
match = re.search(r"Order ID: (\d+), Invoice No: (\d+)", text)
if match:
print(f"Order: {match.group(1)}, Invoice: {match.group(2)}")
# Негруппирующие скобки: валюта не попадает в результат
amounts = re.findall(r"(?:USD|EUR|GBP) (\d+)", "USD 100, EUR 200, GBP 300")
print(amounts) # ['100', '200', '300']
Пример 9. re.sub и re.split
# regex_09_sub_split.py
import re
raw = "apple, banana , orange ,grape"
clean = re.sub(r"\s*,\s*", ", ", raw)
print(clean)
# Разделить по запятым, точкам, пробелам и переводам строк
words = re.split(r"[,\.\s]+", "Python is popular. It is used in web, data, and automation.")
print([w for w in words if w])
Пример 10. Компиляция шаблона
# regex_10_compile.py
import re
texts = [
"Order ID: 12345, Invoice No: 67890",
"Shipment ID: 54321, Tracking No: 98765",
]
number_pattern = re.compile(r"\d+")
for text in texts:
matches = number_pattern.findall(text)
print(matches)
Пример 11. Флаги
# regex_11_flags.py
import re
# Регистронезависимый поиск
print(re.search(r"python", "Python is fun", re.IGNORECASE).group())
# DOTALL: точка совпадает с переводом строки
text = "line1\nline2"
print(re.findall(r".*", text, re.DOTALL))
# MULTILINE: ^/$ для каждой строки
multiline = "Start one\nStart two\nEnd here"
print(re.findall(r"^Start", multiline, re.MULTILINE))