Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
Don’t forget to bring along your reusable shopping bag when you’re out buying your Lunar New Year goodies. Together, we can have a sustainable Year of the Rabbit! 🐰
#BYOB#SayYEStoWasteLess#TowardsZeroWaste
Don’t get a red card especially when it comes to saving the Earth! Say NO to disposables, and YES to reusables.
Together, we can move #TowardsZeroWaste and create a #SustainableSG! #SayYEStoWasteLess#BYOB
This Halloween, make your carbon footprint less scary!
🍿 Having a spooky movie night? Bring along reusable popcorn containers and cups.
👻 Hitting a few haunted houses? Don't forget to keep hydrated with a reusable bottle.
🍭 And if you’re thinking of hitting the sweet shops, keep a reusable bag handy.
#SustainableSG#BYO#BYOB
Bring your reusable bag when you go shopping! Every action counts when it comes to saving planet Earth, and a little goes a long way when it comes to savings 💰
Show the Earth and your wallet some love! #SayYEStoWasteLess#BYO#BYOB
Lock screen reminders are the new sticky notes. So set a trendy reminder to bring your own reusable bag before heading out!
Let’s save the planet, one bag at a time 🛍#BYO#BYOB#SayYEStoWasteLess
Remember to bring your reusable bags when you’re heading out to buy New Year goodies.
This way, you’ll save money while saving the environment. Cheers to a clean, green and prosperous new year. 🧧
#BYOB#SustainableSG#TowardsZeroWaste#LunarNewYear2024
#DidYouKnow the average family in Singapore that buys groceries weekly uses about 1,248 single-use plastic bags annually? 😱
Let’s #SayYEStoWasteLess by bringing along reusable bags when heading out! #BYO#BYOB
Santa’s not the only one with a reusable bag!
When visiting the mall to shop, let’s bring our reusable bags. Together, we can ensure fa-la-la-la-la, la-la-la-less packaging waste. 🛍️
#SayYEStoWasteLess#TowardsZeroWaste#BringYourOwn#BYO#BYOB
Level up your eco-game! ♻️💪 Tote-ally rockin’ a reusable bag = Saving money, slashing trash and giving our environment a healthy splash! 🌿🌏
#BYOB#ZeroWasteNation#Sustainability#SayYEStoWasteLess
For more news and updates on government announcements, follow us on WhatsApp Channels at go.gov.sg/wa-channels!😊
250911 || JohnMaat 𝕏 UPDATE
BYOB Season 3 Final Chef👨🍳
˗ˋˏ YUQI i-dle ˎˊ˗
Yuqi (in charge of all things 𝒮𝐸𝒳𝒴 ⒸⓊⓉⒺ for IDLE)
Would you like to watch the BYOB Wave Show?
> Gi
> Ginio
🔥15 episodes will be released tomorrow at 10 AM (KST)
🔗http://youtube.com/@John_maat
#BYOB#박준형#브라이언
#아이들#idle#우기#YUQI
–🦋
── @GIDLE_UPDATE ──