PYTHONL Telegram 4799
🖥 Шпаргалка по RegEx в Python

📦 Импорт:


import re

🔍 Основные функции модуля re


re.search(pattern, string) # Ищет первое совпадение (где угодно в строке)
re.match(pattern, string) # Ищет совпадение только в начале строки
re.fullmatch(pattern, string) # Проверяет, соответствует ли вся строка шаблону
re.findall(pattern, string) # Возвращает все совпадения в виде списка
re.finditer(pattern, string) # То же, но как итератор Match-объектов
re.sub(pattern, repl, string) # Замена по шаблону
re.split(pattern, string) # Разбиение строки по шаблону


# 🧠 Основы синтаксиса шаблонов

| Шаблон | Что значит |
|---------|-------------------------------------|
| . | Любой символ, кроме \n |
| ^ | Начало строки |
| $ | Конец строки |
| * | 0 или больше повторений |
| + | 1 или больше |
| ? | 0 или 1 повторение |
| {n} | ровно n раз |
| {n,} | n или больше |
| {n,m} | от n до m |
| [] | Символьный класс |
| [^] | Отрицание символьного класса |
| | | Или (`a|b`) |
| () | Группа (захват) |
| \ | Экранирование спецсимвола |

💡 Примеры


re.search(r'\d+', 'ID=12345') # Найдёт '12345' (одно или больше цифр)
re.match(r'^\w+$', 'hello_world') # Вся строка — только буквы/цифры/_
re.findall(r'[A-Z][a-z]+', 'Mr. Smith and Dr. Brown') # ['Smith', 'Brown']
re.sub(r'\s+', '-', 'a b c') # 'a-b-c'
re.split(r'[;,\s]\s*', 'one, two;three four') # ['one', 'two', 'three', 'four']


🎯 Захват групп


text = 'Name: John, Age: 30'
match = re.search(r'Name: (\w+), Age: (\d+)', text)
if match:
print(match.group(1)) # John
print(match.group(2)) # 30


Группы можно называть:


pattern = r'(?P<name>\w+): (?P<value>\d+)'
match = re.search(pattern, 'score: 42')
match.group('name') # 'score'
match.group('value') # '42'


🧱 Комбинированные шаблоны


pattern = r'\b(?:https?://)?(www\.)?\w+\.\w+\b'
text = 'Visit https://example.com or www.test.org'
re.findall(pattern, text) # [['www.'], ['www.']]


⚠️ Полезные советы

• Всегда используйте r'' перед шаблоном, чтобы не экранировать \
re.compile(pattern) ускоряет повторное использование
• Старайтесь избегать re.match — чаще нужен re.search

Быстрая проверка шаблонов

📍 Онлайн-проверка:
- https://regex101.com/
- https://pythex.org/

Хочешь отдельную шпаргалку по re.sub с лямбдами, заменами и функциями внутри, ставь лайк 👍

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM



tgoop.com/pythonl/4799
Create:
Last Update:

🖥 Шпаргалка по RegEx в Python

📦 Импорт:


import re

🔍 Основные функции модуля re


re.search(pattern, string) # Ищет первое совпадение (где угодно в строке)
re.match(pattern, string) # Ищет совпадение только в начале строки
re.fullmatch(pattern, string) # Проверяет, соответствует ли вся строка шаблону
re.findall(pattern, string) # Возвращает все совпадения в виде списка
re.finditer(pattern, string) # То же, но как итератор Match-объектов
re.sub(pattern, repl, string) # Замена по шаблону
re.split(pattern, string) # Разбиение строки по шаблону


# 🧠 Основы синтаксиса шаблонов

| Шаблон | Что значит |
|---------|-------------------------------------|
| . | Любой символ, кроме \n |
| ^ | Начало строки |
| $ | Конец строки |
| * | 0 или больше повторений |
| + | 1 или больше |
| ? | 0 или 1 повторение |
| {n} | ровно n раз |
| {n,} | n или больше |
| {n,m} | от n до m |
| [] | Символьный класс |
| [^] | Отрицание символьного класса |
| | | Или (`a|b`) |
| () | Группа (захват) |
| \ | Экранирование спецсимвола |

💡 Примеры


re.search(r'\d+', 'ID=12345') # Найдёт '12345' (одно или больше цифр)
re.match(r'^\w+$', 'hello_world') # Вся строка — только буквы/цифры/_
re.findall(r'[A-Z][a-z]+', 'Mr. Smith and Dr. Brown') # ['Smith', 'Brown']
re.sub(r'\s+', '-', 'a b c') # 'a-b-c'
re.split(r'[;,\s]\s*', 'one, two;three four') # ['one', 'two', 'three', 'four']


🎯 Захват групп


text = 'Name: John, Age: 30'
match = re.search(r'Name: (\w+), Age: (\d+)', text)
if match:
print(match.group(1)) # John
print(match.group(2)) # 30


Группы можно называть:


pattern = r'(?P<name>\w+): (?P<value>\d+)'
match = re.search(pattern, 'score: 42')
match.group('name') # 'score'
match.group('value') # '42'


🧱 Комбинированные шаблоны


pattern = r'\b(?:https?://)?(www\.)?\w+\.\w+\b'
text = 'Visit https://example.com or www.test.org'
re.findall(pattern, text) # [['www.'], ['www.']]


⚠️ Полезные советы

• Всегда используйте r'' перед шаблоном, чтобы не экранировать \
re.compile(pattern) ускоряет повторное использование
• Старайтесь избегать re.match — чаще нужен re.search

Быстрая проверка шаблонов

📍 Онлайн-проверка:
- https://regex101.com/
- https://pythex.org/

Хочешь отдельную шпаргалку по re.sub с лямбдами, заменами и функциями внутри, ставь лайк 👍

@pythonl

BY Python/ django


Share with your friend now:
tgoop.com/pythonl/4799

View MORE
Open in Telegram


Telegram News

Date: |

Telegram offers a powerful toolset that allows businesses to create and manage channels, groups, and bots to broadcast messages, engage in conversations, and offer reliable customer support via bots. It’s yet another bloodbath on Satoshi Street. As of press time, Bitcoin (BTC) and the broader cryptocurrency market have corrected another 10 percent amid a massive sell-off. Ethereum (EHT) is down a staggering 15 percent moving close to $1,000, down more than 42 percent on the weekly chart. best-secure-messaging-apps-shutterstock-1892950018.jpg Just at this time, Bitcoin and the broader crypto market have dropped to new 2022 lows. The Bitcoin price has tanked 10 percent dropping to $20,000. On the other hand, the altcoin space is witnessing even more brutal correction. Bitcoin has dropped nearly 60 percent year-to-date and more than 70 percent since its all-time high in November 2021. Avoid compound hashtags that consist of several words. If you have a hashtag like #marketingnewsinusa, split it into smaller hashtags: “#marketing, #news, #usa.
from us


Telegram Python/ django
FROM American