Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> text = '''
>>> Alex:8999123456
>>> Mike:+799987654
>>> Oleg:+344456789
>>> '''
Соответственно, для выделения нужных элементов будем использовать группы. Получится такой паттерн:
(\w+):([\d+]+)
Как мы будем формировать словарь из найденных групп?
>>> import re
>>> results = []
>>> for match in re.finditer(r"(\w+):([\d+]+)", text):
>>> results.append({
>>> "name": match.group(1),
>>> "phone": match.group(2)
>>> })
>>> print(results)
[{'name': 'Alex', 'phone': '8999123456'}, ...]
Можно немного сократить запись используя zip
>>> results = []
>>> for match in re.finditer(r"(\w+):([\d+]+)", text):
>>> results.append(dict(zip(['name', 'phone'], match.groups())))
Но есть способ лучше! Это именованные группы в regex. Можно в паттерне указать имя группы и результат сразу забрать в виде словаря.
>>> for match in re.finditer(r"(?P<name>\w+):(?P<phone>[\d+]+)", text):
>>> results.append(match.groupdict())
То есть всё что я сделал, это добавил в начале группы (внутри сбокочек) такую запись:
(?P<group-name>...)
Теперь найденная группа имеет имя и можно обратиться к ней как к элементу списка
>>> name = match['name']
Либо забрать сразу весь словарь методом groupdict()
>>> match.groupdict()
#tricks#regex
🏴Intensa jornada en el mercado de fichajes de la Premier League:
🇧🇪Sebastian Bornauw (26 años) ficha por el Leeds. El acuerdo con el Wolfsburg y los 'whites' se cierra por cerca de €6M.
🏴El delantero escocés Dan Cummings (19 años) es nuevo refuerzo del West Ham. Llega libre tras terminar contrato con el Celtic.
🇸🇳Habib Diarra (21 años) ficha por el Sunderland. Han pagado casi €32M por el mediocampista al Estrasburgo, lo que lo convierte en el fichaje más caro de la historia de los 'black cats'.
🇳🇱El delantero Zepiqueno Redmond (19 años) llega al Aston Villa como agente libre tras quedar desvinculado del Feyenoord.
@LaGuiadelFutbol | #PremierLeague
⚡️Fanton EN: Premier League Gameweek 35 Overview
#PremierLeague#fantasy
Fanton EN presents a preview of Premier League Gameweek 35, covering key matches like Leicester vs. Southampton, Chelsea vs. Liverpool, Brighton vs. Newcastle, and Crystal Palace vs. Nottingham Forest. Each game carries significant implications for fantasy lineups, with Liverpool, Newcastle, and Nottingham still battling for crucial spots.
Source: link
@tonlines
Manchester City es campeón por 4ta vez consecutiva en la Premier League, luego de vencer 3-1 al West Ham
@Fut_planet⚜️#PremierLeague🏴#City🏴
Title races are rarely decided by headlines alone.
Probability shifts long before the table confirms it.
#ManchesterCity#PremierLeague#EdgeMarket#PredictionMarkets
Después de una temporada dónde veíamos al Chelsea de mal en peor logró lo que se veía imposible
Venció 2-1 al Bournemouth, y con un golazo de Moisés Caicedo el conjunto londinense se clasificó a la próxima edición de la UEFA Europa League🟠
@Fut_planet⚜️#PremierLeague🏴#Chelsea🏴#UEL🟠
England Premier League🏴
2026-05-13 19:00 UTC
Manchester City vs. Crystal Palace
Predicted outcome: Manchester City✅
Predicted score: 3:1
Actual: Manchester City 3:0
#ManchesterCity#CrystalPalace
#Football#PremierLeague
England Premier League🏴
2026-04-20 19:00 UTC
Crystal Palace vs. West Ham
Predicted outcome: Draw✅
Predicted score: 1:1
Actual: Draw 0:0
#CrystalPalace#WestHam
#Football#PremierLeague
England Premier League🏴
2026-05-11 19:00 UTC
Tottenham vs. Leeds
Predicted outcome: Leeds❌
Predicted score: 1:2
Actual: Draw 1:1
#Tottenham#Leeds
#Football#PremierLeague
England Premier League🏴
2026-05-01 19:00 UTC
Leeds vs. Burnley
Predicted outcome: Leeds✅
Predicted score: 2:1
Actual: Leeds 3:1
#Leeds#Burnley
#Football#PremierLeague