Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
⭐️#GBPUSD: Weak Market & Bearish Continuation
The charts are full of distraction, disturbance and are a graveyard of fear and greed which shall not cloud our judgement on the current state of affairs in the 📉GBPUSD pair price action which suggests a high likelihood of a coming move down.
📊
🔅GBPUSD Will Move Lower! Short!📉
- - - - - - - -
Take a look at our analysis for 📊GBPUSD.
The market is approaching a significant resistance area 1.352.
Due to the fact that we see a positive bearish reaction from the underlined area, I strongly believe that sellers will manage to push the price all the way down to 1.345 level.
- - - - - - - -
#freesignal#gbpusd
- - - - - - - -
🌐Free Copy Trading: Link
📲Join VIP via Bot:Link
❓Official Contact:@signalprovidercontact
🔅GBPUSD Is Going Up! Long!📈
- - - - - - -
Please, check our technical outlook for 📊GBPUSD.
The market is approaching a key horizontal level 1.349.
Considering the today's price action, probabilities will be high to see a movement to 1.351.
- - - - - - - -
#freesignal#gbpusd
- - - - - - - -
🌐Free Copy Trading: Link
📲Join VIP via Bot:Link
❓Official Contact:@signalprovidercontact
🔅GBPUSD Will Go Down! Short!📉
- - - - - - - -
Please, check our technical outlook for 📊GBPUSD.
The market is testing a major horizontal structure 1.321.
Taking into consideration the structure & trend analysis, I believe that the market will reach 1.315 level soon.
- - - - - - - -
#freesignal#gbpusd
- - - - - - - -
🌐Free Copy Trading: Link
📲Join VIP via Bot:Link
❓Official Contact:@signalprovidercontact