Функция 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
✅Mark your calendar for exciting AMA!
Analyzing 2025's Biggest Opportunity 🔮
Join us today at 12 PM UTC with @CyberChargeJoe ,the Co-Founder of #CyberCharge🔋
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🎄The XMAS holiday season is here!🎁
#CyberCharge Wish you a holiday full of happiness and Gem in bag! 💎
Unlock up to 1500 USDT Gift
📱Join here:https://t.me/CyberChargeGroup
✨Power up,Earn More
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
Congrats 🎊CyberCharge Whitelist Event Ended Successfully!🔚
🔋You’ll enjoy a increase in charger revenue and have first access to profit sharing from the mining pool.⚡️CyberCharge orders are processing ,will be shipped over the next 30 days📆
#Cybercharge Brings the power of web3 charging and mining together!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🚆 The $GOUT train is on the move, and so are your chances to earn! Complete your first charge on #CyberCharge & share 1 MILLION $GOUT! 🤑
It’s easy:
🐦 Follow us & @GOUTCoin
🔋 Charge with the app + comment your APP ID below!
🔁 RT + Tag 2 friends
The market is heating up fast 🔥and so is the reward pool.
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🐾Meet AI Doggy, your loyal companion on the #CyberCharge journey! 🐕
✨Buy, grow, and earn with your digital pet
🔋Keep its health >50% for max mining rewards
💎Boost its value as you nurture it
⚠️Careful—if health hits 0, it’s game over!
Get Ready: https://link.medium.com/qzA4cxdp6Ob
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
↗️ROI So Quick, You’ll Blink Twice!
🔋Charging your devices is now a revenue stream. #CyberCharge makes it REAL with fast returns. Watch how you can earn in record time! 📽
💎Apply for the whitelist with Gem Shards in the Mini App today!
👉http://t.me/CyberChargeBot/whitelist
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🎉Celebrate our partnership with @arbitrum!🎉
To join:
1️⃣RT & Like this post
2️⃣Comment with your BEP20 wallet address and #CyberCharge TG ID
⚡️20 USDT x 5 winners! ⚡️
Get ready to Charge-to-Earn with CyberCharge on arbitrum! 💙🧡
🏆Winners announced in 3 days—don’t miss out! 🚀
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🔋CyberCharge x Movement is here!
⚡️By combining @movementlabsxyz ’s platform with #CyberCharge’s Charge to Earn technology, we’re making every charge count.
Now, users can earn rewards simply by staying powered up, all within a secure and engaging digital ecosystem.
Stay tuned for more!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🚀CyberCharge x EMC Partnership!⚡️We're thrilled to team up with@EMCprotocol to revolutionize blockchain-powered energy solutions!
EMC is a leading AI & DePIN platform that bridges the computing power network and decentralized AI applications!
🔋With the world’s first DePIN Charge-to-Earn (C2E) Network, #CyberCharge brings the power of charging and mining together!
Stay tuned for exciting updates as we unlock new paths for sustainable energy. 🌱
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
Global electricity usage is spiking after decades of stable demand. Now CyberCharge tackle the sustainable energy challenge. But how to earn your ticket to the next-gen of energy networks?
🎬 NEW VIDEO DROP: How to Earn with #CyberCharge!
🎁GIVEAWAY
We’re giving away 5 $USDT to 10 lucky winners!
1️⃣Follow & RT
2️⃣Open the link 👉t.me/CyberCharge copy your TG ID, and paste it here.
3️⃣Screenshot your favorite part of the video and post it below!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🔋Ready to charge up your earnings? 💥
🤑Join the Charge-to-Earn event with #CyberCharge, where EVERYONE wins 100% guaranteed USDT rewards!
💰Earn NOW
🔗http://t.me/daily_gifts_en/74
Don’t miss out, it’s that simple: complete tasks & earn!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
👋Hey #CyberCharge mini APP users! We’ve rolled out some cool new updates:
✨Home upgraded with smooth new animations.
🛑 "Withdraw" button in My Assets now highlighted with extra safety prompts.
🎁Task interface refreshed: updated task lists and Mystery Box rewards shown per task!
💎Invite friends and earn even more Gem Shards!
🌐Global broadcasts—stay informed anytime, anywhere.
Update now for a smoother, safer experience!
🔋t.me/CyberChargeBot
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube