💻 Практические примеры

⚡ Минимальный рабочий пример

import re

emails = "Contact: alice@example.com, bob@test.org"
print(re.findall(r"\w+@\w+\.\w+", emails))

Пример 1. Специальные символы

import re

text = "\tPython 3.12, Java 17, C++ 14!\n"

print("Digits:", re.findall(r"\d", text))
print("Two-digit numbers:", re.findall(r"\d\d", text))
print("Non-digits:", re.findall(r"\D", text))
print("Word chars:", re.findall(r"\w", text))
print("Non-word chars:", re.findall(r"\W", text))
print("Spaces:", re.findall(r"\s", text))
print("Non-spaces:", re.findall(r"\S", text))
print("Any char (except \\n):", re.findall(r".", text))

Пример 2. Классы символов

import re

text = "Report, report, report2, report10"

print(re.findall(r"[rR]eport", text))
print(re.findall(r"[0-9]", text))
print(re.findall(r"[A-Z]", text))
print(re.findall(r"[a-z]", text))
print(re.findall(r"[a-zA-Z]", text))
print(re.findall(r"[^0-9]", text))

Пример 3. Квантификаторы

import re

text = """
Orders: ID123, ID4567, ID89
Numbers: 123-45-67, 321-45-67
Prices: 100$, 199.50$, 99.99€, 0.49€, .99€
File names: report.txt, report2.txt, report10.txt
"""

print(re.findall(r"\d+", text))
print(re.findall(r"\d{3}-\d{2}-\d{2}", text))
print(re.findall(r"\d+\.\d+", text))
print(re.findall(r"ID\d{2,}", text))
print(re.findall(r"report\d*\.txt", text))
print(re.findall(r"report\d?\.txt", text))
print(re.findall(r"report\d{1,2}\.txt", text))

Пример 4. Жадные и ленивые квантификаторы

import re

text = "<div>Hello</div><div>World</div>"

greedy = re.findall(r"<.*>", text)
lazy = re.findall(r"<.*?>", text)

print("Greedy:", greedy)
print("Lazy:", lazy)

Пример 5. Якоря

import re

text = "Hello world! Welcome to world"

print(re.findall(r"^\w+", text))
print(re.findall(r"\w+$", text))

text2 = "category wildcat education _cat_ catalog"
print(re.findall(r"\w+cat\w+", text2))
print(re.findall(r"\bcat\w*", text2))
print(re.findall(r"\w*cat\b", text2))

text3 = "X123X 234 4567X X999"
print(re.findall(r"\B\d+\B", text3))

Пример 6. Группы

import re

text = "Order ID: 12345, Invoice No: 67890"

match = re.search(r"Order ID: (\d+), Invoice No: (\d+)", text)
if match:
    print("Order ID:", match.group(1))
    print("Invoice No:", match.group(2))

# Негруппирующие скобки
text2 = "USD 100, EUR 200, GBP 300"
matches = re.findall(r"(?:USD|EUR|GBP) (\d+)", text2)
print(matches)

Пример 7. split и sub

import re

text = """Python is popular. It is used in web development, data science,
and automation. Many developers choose Python for its simplicity."""

words = re.split(r"[,\s.]+", text)
print(words)

text2 = "apple,   banana ,  orange ,grape"
clean_text = re.sub(r"\s*,\s*", ", ", text2)
print(clean_text)

Пример 8. Компиляция шаблона

import re

texts = [
    "Order ID: 12345, Invoice No: 67890, Ref: ABC9876",
    "Shipment ID: 54321, Tracking No: 98765, Customer Ref: XYZ123",
    "Invoice 22222 processed successfully.",
]

number_pattern = re.compile(r"\d+")

for text in texts:
    matches = number_pattern.findall(text)
    if matches:
        print(f"Matches: {matches}")

Пример 9. Простое замыкание

def outer_function(text: str):
    def inner_function():
        print(text)
    return inner_function


closure = outer_function("Captured text")
closure()

Пример 10. Замыкание с изменением состояния

def counter():
    count = 0

    def increment() -> int:
        nonlocal count
        count += 1
        return count

    return increment


counter_function = counter()
print(counter_function())
print(counter_function())
print(counter_function())

Пример 11. Фабрика фильтров

def create_filter(border: float):
    def filter_value(value: float) -> bool:
        return value > border
    return filter_value


greater_than_five = create_filter(5)
print(greater_than_five(7))
print(greater_than_five(3))

Пример 12. Декоратор

import time


def timing_decorator(func):
    def wrapper():
        start_time = time.time()
        func()
        end_time = time.time()
        print(f"Function {func.__name__} took {end_time - start_time:.5f} seconds")
    return wrapper


@timing_decorator
def slow_function():
    time.sleep(0.1)
    print("Done")


slow_function()

Как запустить в VS Code

  1. Создайте папку python-fundamentals-practice/lesson-63/.
  2. Создайте файл summary_session_16.py и скопируйте в него примеры.
  3. Откройте терминал в VS Code (Ctrl + `).
  4. Активируйте виртуальное окружение: venv\Scripts\activate (Windows) или source venv/bin/activate (Mac/Linux).
  5. Запустите: python summary_session_16.py