Функция 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
🎆 Happy New Year! #TPFam
We wish you glowing health, top-tier security for all your assets, and a market that stays eternally bullish.
🌕 May this year bring you boundless prosperity and exciting opportunities in crypto!
💥Big Congrats! #TPFam
🏆Check if you are on the PFPAsia NFT Whitelists Giveaway Winner List!👇
https://docs.google.com/spreadsheets/d/1Nx66DZYX768_CETOgCFXi8QRK9jXp5cvP0Np4LOzPk4/edit#gid=0
🟥 Check your RED👇
https://whitelist.pfp.asia
🔴For more details, follow PFPAsia.
💥Big Congrats!
🏆Check if you are on the 500 $NOAH Giveaway Winner List! (200 Winners) Noah_DeFi
👉
https://docs.google.com/spreadsheets/d/1LpNzHNqPW6PJD2fcqIWuteLWhBWguX9H4Tyti740ym4/edit#gid=0
🎁The rewards will be distributed by Noah_DeFi within A week!
💙Thanks for your participation! #TPFam
If you have any questions, you can join TokenPocket's Telegram to get more info.
👉https://t.me/tokenPocket_en
【Details】https://twitter.com/TokenPocket_TP/status/1752260036150358373
【Powered By】Crypto Box
🌊 2025 has been a year filled with growth, challenges, and continued progress.
To our #TPFam — your support has powered every step forward. 💙
Thank you for building and growing with TokenPocket.
Dive into the #TokenPocket 2025 Annual Report 👇
https://tokenpocket-gm.medium.com/tokenpocket-2025-annual-report-7820b638a1d1
https://x.com/TokenPocket_TP/status/2013901810453410143?s=20
With the unwavering support from [#TPFam](https://twitter.com/hashtag/TPFam), 2023 has been a year of significant breakthroughs! 🎯
Always have a BIG Thanks in my mind and thank you for helping us make everything possible! 💙
Dive into the [#TokenPocket](https://twitter.com/hashtag/TokenPocket) 2023 Annual Report 👇
https://tokenpocket-gm.medium.com/tokenpocket-2023-annual-report-3b9bd4025f83
【Details】https://twitter.com/TokenPocket_TP/status/1754399781915631720
【Powered By】Crypto Box
💥Big Congrats!
🏆Check if you are on the Scopechat $200 Giveaway Winner List! (20 Winners) ScopeProtocol
👉https://docs.google.com/spreadsheets/d/1HJmeNoN4ZLKh8fuvEadmNsHLOD-_33VjFvIW0S6pptg/edit#gid=0
🎁The rewards will be distributed by ScopeProtocol within A week!
💙Thanks for your participation! #TPFam
If you have any questions, you can join TokenPocket's Telegram to get more info.
👉https://t.me/tokenPocket_en
How to check your rewards?
🎯Download TokenPocket
👉https://www.tokenpocket.pro/
👉https://extension.tokenpocket.pro/
✅Check on your #TokenPocket Polygon Wallet!
【Details】https://twitter.com/TokenPocket_TP/status/1750361152532664546
【Powered By】Crypto Box
🧑🎄Merry Christmas! #TPFam#TokenPocketChristmas
❄️May your wallets be filled with joy, your transactions be seamless, and may the blockchain of happiness bless you with endless prosperity.
Wishing you a Merry Christmas and a crypto-filled New Year! 🚀🌟
👉https://www.tokenpocket.pro/
【Details】https://twitter.com/TokenPocket_TP/status/1738895386377601385
【Powered By】Crypto Box
💥Big Congrats!
🏆Check if you are on the 1,000 [#ZETA](https://twitter.com/hashtag/ZETA) Giveaway Winner List! (50 Winners)
👉https://docs.google.com/spreadsheets/d/1tZ2uGSZDAyX7tj_pSWCrOUwn1f_kDxHBBpJnMRjM6t0/edit[#gid](https://twitter.com/hashtag/gid)=0
🎁The rewards have been distributed, please check your [#TokenPocket](https://twitter.com/hashtag/TokenPocket) [@zetablockchain](https://twitter.com/zetablockchain) wallet!
Guide👉https://help.tokenpocket.pro/en/wallet-operation/how-to-create-a-wallet/zetachain
💙Thanks for your participation! [#TPFam](https://twitter.com/hashtag/TPFam)
If you have any questions, you can join TokenPocket's Telegram to get more info.
👉https://t.me/tokenPocket_en
【Details】https://twitter.com/TokenPocket_TP/status/1754412672639193249
【Powered By】Crypto Box
💙Thanks to all the #TPFam who participated in the #TP6Anni celebration!
🏆Check if you are on the #TP6Anni Giveaway Winner List!
1️⃣ 50 BitlayerLabs Lucky Helmet NFT
👉https://docs.google.com/spreadsheets/d/1qjIkzt1_CM_LfNaoy4vVIrqSmB5hF4oAN5pIScYgeQM/edit#gid=0
2️⃣ $2,000 esMP token Giveaway
👉https://docs.google.com/spreadsheets/d/1tt_AiQmQYZk3EFS-6hEwTZFBI0iTcJDK6YD110TZeQU/edit#gid=0
3️⃣1,000 Piggy Boxes V3 Giveaway
👉https://docs.google.com/spreadsheets/d/1_Aj9cgq0SdyJHQjztl-TWGwHQb_NHgWIbaonwzSH7vA/edit#gid=0
4️⃣$3,000 $TNA and 50 Tapnames Whitelists Giveaway
👉https://docs.google.com/spreadsheets/d/1ZiCOS_nQ897Vj5p5TgoMi607hCCk2IILhwVn6-w-MjE/edit#gid=0
💙Thanks for your participation! If you have any questions, please join https://t.me/tokenPocket_en.
💥Big Congrats!
🏆Check if you are on the 1000 USDT Giveaway Winner List! (100 Winners) ChintaiNetwork ChintaiNexus
👉https://docs.google.com/spreadsheets/d/1sY-0fZgfrBZC2UQsZPKvN_Dl3V1A0nG-cR7iOpXlbcM/edit#gid=0
🎁The rewards have been distributed, please check your #TokenPocket#BNBChain wallet!
💙Thanks for your participation! #TPFam
If you have any questions, you can join TokenPocket's Telegram to get more info.
👉https://t.me/tokenPocket_en
【Details】https://twitter.com/TokenPocket_TP/status/1752986641118134673
【Powered By】Crypto Box
💕💕Happy #Thanksgiving! 🐔
Wishing You a Joyous Thanksgiving!
Thank you for the unwavering support from #TPFam and #TokenPocket Partners!
Keep Building! 🏃🏃♂️🏃♀️
【Details】https://twitter.com/TokenPocket_TP/status/1727620906225373326
【Powered By】Crypto Box