Функция 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
💥CLOSED BETA TESTERS SELECTED!
Attention all #QuasarK enthusiasts!
We are thrilled to announce that we have selected our closed beta testers for the upcoming QuasarK app on iOS and Android 🎉
To our selected beta testers, congratulations! 🥳 You are the chosen ones who will get an exclusive sneak peek 👀 into the app's features, functionalities, as well as a bunch of exciting perks. Your valuable feedback and insights will help us refine and enhance🚀 the QuasarK experience for everyone.
✅ We have granted all beta testers a special role in our QuasarK Discord server. This role comes with access to a private channel dedicated to the closed beta testing. There, we will keep you updated on all the important information📩 regarding the app's access, updates, and any announcements related to the beta testing phase.
Make sure to check your Discord notifications for the role assignment and say hello in the private chats📲💬
We are incredibly excited 🙈 to have you on board, and we can't wait to embark on this beta testing journey together. Your input and feedback will play a vital role in shaping the final release of QuasarK 💫, and we greatly appreciate your dedication and involvement in this process.
Thank you once again 😍 for being part of the QuasarK community and for your continued support. Stay tuned🔔 for more updates, surprises, and the official launch of QuasarK coming soon!
📢CLOSED BETA WHITELIST CLOSED
Attention, QuasarK Community: the application period for our closed beta is now officially closed. We want to express our heartfelt thanks ❤️ to everyone who applied and showed their interest in being a part of this exclusive testing phase. Your support and enthusiasm mean the world to us! 👏
🚀 But hold on tight, because the journey is just getting started! In a matter of days we’ll be reaching out to our whitelisted beta testers🏆. If you made it to the whitelist, keep an eye on your notifications and direct messages 📩 as we will be sharing important updates and instructions with you. BEWARE OF SCAM!
Stay tuned for more updates and announcements 👀 as we continue to make progress towards the launch of QuasarK. We appreciate your ongoing support and look forward to embarking on this exciting journey together!
#QuasarK#ClosedBeta#BetaTesters#ComingSoon
💫📝 JOIN QUASARK BETA
Calling all crypto enthusiasts!
We are thrilled to announce that QuasarK is to launch its closed beta and we need OGs willing to be the first to experience the power and convenience of the next-gen wallet 🙌
🔍 Become a Beta Tester and play an active role in refining and improving 💎 the wallet before its public release. And your effort will be rewarded 💰
💥 How to Join QuasarK Beta
1️⃣ Participate in this campaign: https://zealy.io/c/quazark/invite/yJwJUITfB-ehsbeVWcaOP
2️⃣ Complete all the tasks and get 'QuasarK Closed Beta' Discord role. Lucky beta testers will be selected from all holders of this role!
🚀 Don't miss this incredible opportunity to be at the forefront of crypto innovation. Join the QuasarK beta testing program ✅, contribute to the development of a game-changing multichain wallet. The number of testers is very limited, and the rewards are well-worth it!
Together, let's revolutionize the way we manage our digital assets!
#QuasarK#Crypto#DeFi#Web3#Beta
🚀 Last Call for the QuasarK Closed Beta Whitelist
Are you ready to experience the future of cryptocurrency wallets? The countdown is on ⏰, and we don't want you to miss out on this exciting opportunity!
Here's why you want to be part of our closed beta:
1️⃣ Unrivaled Security: Quasark ensures the safety of your funds like never before. Rest easy, knowing your assets are protected.
2️⃣ User-Friendly Interface: Effortlessly navigate through features, send and receive funds, and stay in control of your financial future.
3️⃣ Cutting-Edge Features: From instant swaps to customizable interface, we've got you covered with a suite of powerful tools.
4️⃣ Prices&Market trends: Access insightful charts and information to make informed investment decisions.
👉 Don't wait any longer! Secure your spot before SUNDAY:
https://zealy.io/c/quazark/invite/yJwJUITfB-ehsbeVWcaOP
#Quasark#CryptoWallet#ClosedBeta#DigitalAssets#DeFi