Функция sub в regex может принимать функцию в качестве аргумента repl.
📄 Из документации:
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
То есть для каждого совпадения будет вызвана функция для вычисления замены вместо замены на одну и ту же строку для всех совпадений.
Иными словами, для замены разных совпадений на разные строки не потребуется запускать re.sub() много раз для каждой строки замены. Достаточно определить функцию, которая вернёт строку для каждого из совпадений.
Описание слишком запутанное🤔, давайте лучше рассмотрим на простом примере:
Создаем карту замены. То есть какие строки на какие требуется менять.
remap = {
'раз': '1',
'два': '2',
'три': '3',
'четыре': '4',
'пять': '5',
}
Пишем функцию поиска строки для замены. Единственным аргументом будет объект re.Match.
Используя данные этого объекта мы вычисляем замену on-the-fly!
def get_str(match: re.Match):
word = match.group(1)
return remap.get(word.lower()) or word
Пример текста.
text = '''Раз Два Три Четыре Пять
Вместе будем мы считать
Пять Четыре Три Два Раз
Мы считать научим вас
'''
Теперь запускаем re.sub и вместо строки замены (repl) подаём имя функции.
(Данный паттерн ищет отдельные слова в тексте)
>>> print(re.sub(r'(\w+)', get_str, text))
1 2 3 4 5
Вместе будем мы считать
5 4 3 2 1
Мы считать научим вас
Думаю, достаточно наглядно 🤓
#libs#regex
Лето в разгаре, и мы решили:
Почему бы не раздать то, что вы любите больше всего?
FRHT #GIVEAWAY
Разыгрываем 10 футболок из новой коллекции FRHT 🔥
Условие участия простое — Подписаться на этот канал 🏁
*если ещё не с нами
Мы случайным образом выберем 10 победителей и отправим выбранные футболки
Итоги 25 июля. Поехали 🚀
🎉Bitget Wallet x All At Once #Giveaway🎉
🕙Event duration: August 23 - August 30, 2024
💰Rewards:
🚀$3,000 worth of TON for 300 lucky participants🚀
5M xAAO prize pool is shared equally among all participants
How to join:
1️⃣ Follow @BitgetWallet + @AAO_Game
2️⃣ Join the AAO & Bitget Wallet Telegram groups:
3️⃣ Join the All At Once Bot and complete one game battle
4️⃣ Fill out the Google form to receive your reward
🚀 Material Widgets - Everything is Now Available.
Grab it today 👉✨ Special Launch Offer
https://play.google.com/store/apps/details?id=com.jndapp.material.widgets.pack
🎁#Giveaway 15 Promo Codes
♥️, repost, and comment to Participate.
Join Giveaway
🔥
🚀 Material Widgets - Everything is Now Available.
Grab it today 👉✨ Special Launch Offer
https://play.google.com/store/apps/details?id=com.jndapp.material.widgets.pack
🎁#Giveaway 15 Promo Codes
♥️, repost, and comment to Participate.
Join Giveaway
🔥
💝GAMEWTB Valentine's Day Giveaway - Steam Gift Card💝
Happy Valentine’s Day!💖 As a token of our appreciation for your continued support, the GAMEWTB TEAM has prepared a special gift🎁 for you.
💸Prize: $5 Steam Gift Card
📅FROM NOW - FEB 17, 2025
=How to Participate=
📲Follow our X: x.com/PC_Gamewtb
❤️♻️LIKE & RETWEET THIS POST☝️
⏰Winner will be announced on Feb 17th
✅COMMENT "DONE" UNDER THIS POST☝️
👀Wait our DM💌
Limited Time Event – Don’t Miss Out!
🤩Whether you're spending Valentine’s Day solo or with a special someone, remember to love yourself! GAMEWTB will keep bringing you the latest game news and exciting events.
Join Gamewtb Group for GIVEAWAYS!
#GIVEAWAY
💚🍀🌱 FARMERS, LISTEN UP! 💎✨
One of the LAST chances to grab OG role 🎖 and it’s about to go CRAZY 😤🔥
We're dropping a massive GIVEAWAY 🎁 /w 30 winners
EACH GETS 0.1 SOL 🤑 + OG 👑
How to join:
1. Join our X (Twitter)
https://x.com/ggpweb3
2. Join our Discord
https://discord.gg/gg-paradise
3. Leave wallet in #giveaway channel
4. Stay active on server
Results in Friday 🕶
Let’s make it loud before the farm goes wild 🌿🚀
💥500 QUACK AI NFTs and 200,000 QUACK Points Giveaway to TokenPocket users!
👉https://app.galxe.com/quest/TokenPocket/GC6YCtmDkS
🍾500 lucky winners will each receive a QUACK AI NFT!
🎯 Winners will also be eligible to earn an extra 400 points by interacting with the QUACK AI platform.
#giveaway
💧Airdrop : Lifestory💧
📣Complete Task: ➕ $6000 #Giveaway - 4 Days contest
🏆Winners: For All Valid Users
📅End date: After 4 Days
💎Ratings: ⭐️⭐️⭐️
🔛Galaxy Airdrop Gleam Click Here🔛
🌀 Follow on Twitter and retweet the pinned post.
🌀 After Done Airdrop Task then Create your wallet.
📡Enter your information to the Airdrop Gleam.
🗞Note: All airdrop steps should be completed.
⛵️Business Inquiry: Admin || Admin2
💥Big Congrats!
🏆Check if you are on the ZoomManor #Giveaway Winner List!
👉https://docs.google.com/spreadsheets/d/1QQ1rdc3jnt6BAhWL_8qhJJe56KyxSqF8BvCk21dLvSk/edit#gid=0
🎁The rewards will be distributed by ZoomManor before Jan 5th. ZoomManor
💙Thank you all very much for your participation!
If you have any questions, you can join TokenPocket's Telegram to get more info.
👉https://t.me/tokenPocket_en
🪂New airdrop: FOBOCLUB x MEXCGlobal Collab Event #giveaway
💰Reward: 50 FOBO CLUB WLs (NFT)
📅Distribution: uncertain
🔗Airdrop Link: airdrop page
🔹Complete all tasks of the airdrop
Disclaimer: Airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop for free!
🪂Airdrop: Mystery Box #Giveaway
💰Reward: $3,000
👨💼 Winner: All participants
📅 TIME:10/03/2022 07:00 AM - 10/09/2022 11:00 PM UTC
🔗Airdrop Link: airdrop page
🔹Complete all tasks of the airdrop
Disclaimer: Airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop for free!