Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
🪙YouTube Tasks
Complete and earn 🪙 in Major!
▶️Watch Video #1
Reward: +5,000 ⭐️
Code: 070624
▶️Watch Shorts #4
Reward: +1,500 ⭐️
Code: 159390
🪙 Enter the codes and collect your stars now!
🔔Subscribe
➡️Join Major
➖➖➖➖➖➖➖➖➖➖
#major#crypto#taptap
🪙Major:New Combo of the Day October 18!
➡️Number sequence: 2:12:4:10
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 14!
➡️Number sequence: 6:3:4:5
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 12!
➡️Number sequence: 10:14:12:1
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe 👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 11!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 10!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 9!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 8!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 7!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day September 23!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day September 22!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day September 19!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap