Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
🔒100% Security Rate on SLEX Centralized Exchange!🔒
📖We're thrilled to inform you that Hacken, a trusted crypto and blockchain security audit firm, has rigorously reviewed the SLEX Centralized Exchange's code🔍
🔥What's the result? — A flawless review with ZERO vulnerabilities or code errors detected!
🎉This means SLEX proudly holds a 100% security rating as per Hacken's audit☄️
Check this out: hacken.io/audits/slex/
🤝Join SLEX platform, deposit your account, and trade with confidence, knowing that our platform meets the highest security standards in the industry🛡️
#SLEXSafety#HackenAudit#SecureTrading
Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🔓🌐 With the expanding digital horizon, ensuring the security of crypto assets is a task that cannot be underestimated.
SLEX platform is dedicated to high level of security and so officially joining the Crypto Currency Security Standard (CCSS)! 🎉
CCSS is a universally recognized security standard specifically designed for cryptocurrencies. It's like a superhero's shield that secures key generation and storage, robust transaction processes! 🛡️
🤔What does this mean for SLEX users?
Simple – it means an even more robust assurance that your digital assets are safe and secure.
So join SLEX - the bastion of crypto security and discover your trading ideas! 🎯💪
#SLEX#CryptoSecurity#CCSS#SecureTrading
Email | Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🔒🌐 Commodity Proof of Reserves - Trusted, Public, and Secure Storage
We are thrilled to unveil Commodity Proof of Reserves, an innovative solution that ensures unwavering trust, transparency, and security in commodity storage.
Through our strategic partnership with a globally renowned mining company, in collaboration with SLEX, we guarantee a steady supply of liquidity and a secure trading environment. Our collaboration ets the highest standards of reliability and integrity.
Our mining operations cover multiple cities in the Democratic Republic of Congo (DRC): Lubumbashi, Kakanda, and Likasi. This extensive network taps into abundant resources, providing an impressive $3 billion USD supply 📝
We understand the critical importance of trustworthy storage and protection in today's dynamic market. Through advanced blockchain technology, we've created a system that ensures complete transparency and validation of reserves. This approach instills confidence in our valued clients and partners.
Commodity Proof of Reserves is a testament to our commitment to innovation, security, and reliability. With our trusted partner and vast resources, we aim to reshape commodity trading, setting new standards for excellence 📌
👉🏻 Join us Now and Stay Tuned For Updates and Developments: Slex.io
#CommodityProofOfReserves#TrustedStorage#SecureTrading#BlockchainInnovation