Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
🔥NEW RELEASE🔥
😁Duck Under Masterclass by Cole Abate😁
➡️The Duck Under combines pressure and speed, blending the control of traditional passing with the tempo and sharpness of the modern game, allowing the guard passer to dictate the pace of the fight.
➡️The Masterclass includes more than 5+ hours of entries, concepts, transitions, and submissions. Throughout the 40 classes, Cole demonstrates the effectiveness of the position, and how the Duck Under completely neutralizes the guard player by removing their ability to setup sweeps or submissions.
$̶1̶7̶9̶😍$19.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#ColeAbate#GuardPassing#Gi#AOJ
💁♀️Buy
💁♀️
😁Modernized Headquarters Passing By Shawn Melanson😁
➡️Unlock the secrets to one of the most dominant and versatile passing positions in Brazilian Jiu-Jitsu with Modernized Headquarters Passing by Shawn Melanson
➡️As an up-and-coming No-Gi competitor who has conquered tournaments at the highest levels, Shawn brings his proven expertise directly to your training. In this comprehensive instructional series, he breaks down the Headquarters Position, a game-changing technique that can be used against nearly every guard in the sport.
➡️With step-by-step guidance, Shawn reveals how to enter, control, and pass from the Headquarters Position, offering you a wide array of strategic options to dominate your opponent.
$79😍$9.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#ShawnMelanson#BJJFanatics#GuardPassing#NoGi#Headquarters
💁♀️Buy
💁♀️
🔥NEW RELEASE🔥
😁Things I Didn't Show To Craig Jones: Maintaining An Advantage Over Time - Outside Passing By Jozef Chen😁
➡️Unlock the secrets to unstoppable no-gi guard passing with JPoint Camping, the latest BJJ instructional from one of the most elite no-gi competitors today, Jozef Chen.
➡️In this systematic instructional, Jozef guides you through the step-by-step process of dismantling even the most difficult no-gi guards, using a series of tried-and-true methods refined over years of high-level competition.
➡️Transform your guard passing into a dominant, methodical force, and learn how to effortlessly break through any guard. With Jozef Chen’s expert guidance, you’ll develop the mindset, precision, and fluidity needed to consistently control the pace and flow of your no-gi matches.
$127😍$11.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#JozefChen#CraigJones#CJI#GuardPassing
💁♀️Buy
💁♀️