Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
🚀 Gas-Free Transfers are now live on Solana!
With TokenPocket, enjoy:
✨ 3 free transfers every day
✨ Fast, reliable on-chain transactions
Make every move cost-effective with #GasFreeWallet💙
→ https://help.tokenpocket.pro/en/wallet-faq-en/solana-wallet/gas-free-service-on-solana
⛽️Gas Fee? Gas Free!
No more worrying about running out of $TRX for gas fees — TokenPocket now supports $USDD for gas payments, with a limited-time subsidy!
Enjoy a smoother, faster, and more efficient experience on the TRON network. #StablecoinWallet#GasFreeWallet
🎥 Watch how it works: https://youtube.com/watch?v=gndDfJBN_cg
🔋Gas-Free Stablecoin Transfers? TokenPocket makes it real.
→ https://help.tokenpocket.pro/en/wallet-operation/stablecoin/gas-free
✅Zero fees, lightning-fast transactions on BNBCHAIN & TRON
✅Trusted by 30M+ users worldwide - fast, affordable, secure.
Experience the future of stablecoin wallets with TokenPocket. #StablecoinWallet#GasFreeWallet
📝 TokenPocket Monthly Report — December 2025
→ https://tokenpocket-gm.medium.com/tokenpocket-monthly-report-december-2025-c0cd0518efa7
In December, TokenPocket launched a series of measures under the theme of technological innovation and community activities, covering multiple dimensions such as multi-chain function upgrades, trading experience, ecosystem cooperation expansion, security protection enhancements, and transfer experience optimization.
🎯#SAFU
TokenPocket's anti-phishing function is comprehensive. Combined with security functions like Privacy Wallet and Passphrase, it jointly safeguards the security of your assets.
🎯#StablecoinWallet & #GasFreeWallet
TokenPocket now supports Multi-Chain Gas Payment with Stablecoins on base, arbitrum, and BNBCHAIN. Combined with 0 gas fee transfers services on trondao, solana, and BNB Chain, this further solidifies TokenPocket as your go-to choice for a Stablecoin Wallet.
📍 All In One, All in TokenPocket
https://t.co/OVU2yXAPqA
🟥The Gas-Free Transfer on TRON on TokenPocket is live! 🍌
😍Get your TRON Gas Coupons NOW!
✅Comment [Gas-Free On TokenPocket] below👇
💰For 100 winners!
💎With TokenPocket’s TRON Gas Coupons, you can save up to 100% on gas costs on the TRON Network, allowing you to enjoy truly GAS-FREE transfers and trading experiences on TRON!
Details👉https://help.tokenpocket.pro/en/wallet-faq-en/tron-wallet/coupon
#TRON#TokenPocket#GasFree#ZeroGas#GasFreeWallet