Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
Your singing talent can win you an incredible prize!
Participate in the much-awaited event #YuvaPratibha Singing Talent Hunt and win up to ₹1.5 LAKH!
Visit: https://innovateindia.mygov.in/singing-challenge/
Unleash your imagination and add vibrant colours to the world of innovation with the #YuvaPratibha Painting Competition.🎨🖌️
Join the celebration of creativity on #MyGov and stand a chance to win ₹1 lakh.
#YuvaPaintYourDreams
Visit https://innovateindia.mygov.in/painting-challenge/
Unleash your imagination and add vibrant colours to the world of innovation with the #YuvaPratibha Painting Competition.🎨🖌️
Join the celebration of creativity on #MyGov and stand a chance to win ₹1 lakh.
#YuvaPaintYourDreams
Visit https://innovateindia.mygov.in/painting-challenge/
Unleash your imagination and add vibrant colours to the world of innovation with the #YuvaPratibha Painting Competition.🎨🖌️
Join the celebration of creativity on #MyGov and stand a chance to win ₹1 lakh.
#YuvaPaintYourDreams
Visit https://innovateindia.mygov.in/painting-challenge/
Calling all foodies and culinary enthusiasts👩🍳👨🍳
Put your cooking skills to the test and stand a chance to win ₹1 lakh by participating in the #YuvaPratibha Culinary contest. Let's discover the versatility of millet in the kitchen.
#PCC
#AmritMahotsav
Visit: https://innovateindia.mygov.in/culinary-challenge/
देश के सुप्रसिद्ध संगीतकार शंकर महादेवन के सामने अब आपके पास है अपनी गायन प्रतिभा दिखाने का सुनहरा अवसर 🤩
#MyGov द्वारा आयोजित #YuvaPratibha गायन प्रतियोगिता में भाग लें और देश भर में छा जाएं 🎤🎶
भाग लेने हेतु विजिट करें: https://innovateindia.mygov.in/singing-challenge/
#SingWithYuvaPratibha#AmritMahotsav
देश के सुप्रसिद्ध संगीतकार शंकर महादेवन के सामने अब आपके पास है अपनी गायन प्रतिभा दिखाने का सुनहरा अवसर 🤩
#MyGov द्वारा आयोजित #YuvaPratibha गायन प्रतियोगिता में भाग लें और देश भर में छा जाएं 🎤🎶
भाग लेने हेतु विजिट करें: https://innovateindia.mygov.in/singing-challenge/
#SingWithYuvaPratibha#AmritMahotsav
देश के सुप्रसिद्ध संगीतकार शंकर महादेवन के सामने अब आपके पास है अपनी गायन प्रतिभा दिखाने का सुनहरा अवसर 🤩
#MyGov द्वारा आयोजित #YuvaPratibha गायन प्रतियोगिता में भाग लें और देश भर में छा जाएं 🎤🎶
भाग लेने हेतु विजिट करें: https://innovateindia.mygov.in/singing-challenge/
#SingWithYuvaPratibha#AmritMahotsav
🎤🌟 Calling all aspiring singers!
Your moment in the spotlight has arrived. Join the electrifying '#YuvaPratibha Singing Talent Hunt' on #MyGov and let your voice mesmerize the nation.
🎶✨
Visit: https://innovateindia.mygov.in/singing-challenge/
#SingWithYuvaPratibha
#AmritMahotsav
Showcase your singing talent in front of legendary singer Shankar Mahadevan!
Participate in #YuvaPratibha Singing Talent Hunt on #MyGov
Visit: https://innovateindia.mygov.in/singing-challenge/
#SingWithYuvaPratibha#MyGov#AmritMahotsav
Showcase your singing talent in front of legendary singer Shankar Mahadevan!
Participate in #YuvaPratibha Singing Talent Hunt on #MyGov
Visit: https://innovateindia.mygov.in/singing-challenge/
#SingWithYuvaPratibha#MyGov#AmritMahotsav
Showcase your singing talent in front of legendary singer Shankar Mahadevan!
Participate in #YuvaPratibha Singing Talent Hunt on #MyGov
Visit: https://innovateindia.mygov.in/singing-challenge/
#SingWithYuvaPratibha#MyGov#AmritMahotsav