Функция 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
🆕We've released a new version of TokenPocket on Android.
🔺2.7.0🔺
🔵Support EIP-7702-based Dust Cleaner function.
🔵Optimize the trading experience.
🔵Optimize users’ experience.
You can upgrade your #TokenPocket via Google Play or the official website. 🔗https://tp.xyz
🆕We've released a new version of TokenPocket on Android. 🔺2.6.0🔺
🔵Fully upgrade the trading experience.
🔵Add PnL analysis on the Asset page.
🔵Enhance the market page with more comprehensive data display.
🔵Optimize users’ experience.
You can upgrade your #TokenPocket via Google Play or the official website. 🔗https://tp.xyz
🆕We released TokenPocket's new version on Android. 🔺2.4.7🔺
🔵Upgrade the wallet security backup feature.
🔵Support EIP-4527 Protocol.
🔵Meme Mode supports TRON network.
🔵Add security reminders for custom nodes.
🔵Support the Notifications for Multi-Sig wallet transactions.
🔵Optimize token search functionality on the Asset page.
🔵Optimize the experience on the Solana network.
🔵Optimize users’ experience.
You can upgrade your #TokenPocket via Google Play or the official website.
🔗https://tp.xyz
🆕⛓svmBNB is now live on TokenPocket.
svmBNB is a high-performance SVM chain developed by the SOON team for BNB Chain, based on the SOON Stack.
💙How to create/import a svmBNB wallet on #TokenPocket?
Guide👉https://help.tokenpocket.pro/en/wallet-operation/how-to-create-a-wallet/svmbnb
🎈Discover the svmBNB Ecosystem with Your TokenPocket!
📱https://tp.xyz
💻https://extension.tokenpocket.pro
📣 Our New Official Website: https://www.tp.xyz/🌐
It will operate alongside http://tokenpocket.pro to provide users with a more stable and efficient access experience.
A smarter, easier way to explore Web3. #TokenPocket
👉https://www.tp.xyz/
👉https://www.tokenpocket.pro/
🆕We released TokenPocket's new version on Android and iOS.
🔺Android: 2.4.5
🔺iOS: 2.6.6
🔖Details 👇
🔵Support BEP-414, enabling users to pay $USDT or other tokens as gas costs.
@BNBCHAIN
🔵Support the PnL display on the Market page.
🔵Support MEV Node Detection service.
🔵Support deleting the wallet address on Recent Transfer.
🔵Support for Smart Address tagging.
🔵Update the default token icons.
🔵Optimize the Secret Recovery Phrase backup process.
🔵Optimize the wallet synchronization feature.
🔵Optimize Market data display.
🔵Optimize the wallet service on Solana and TON.
📱You can upgrade your #TokenPocket via Google Play, App Store, or the official website.
🔗https://tokenpocket.pro
🆕Eclipse is now live on TokenPocket.
Eclipse Mainnet is Ethereum's first Solana Virtual Machine (SVM) network. Eclipse Mainnet combines the best pieces of the modular stack.
💙How to create/import an Eclipse wallet on #TokenPocket?
Guide 👉https://help.tokenpocket.pro/en/wallet-operation/how-to-create-a-wallet/eclipse
🎈Discover the Eclipse Ecosystem with Your TokenPocket!
👉https://tokenpocket.pro
🆕We released TokenPocket's new version on Android and iOS.
🔺Android: 2.4.3
🔺iOS: 2.6.1
🔵Market and Trading Sections Upgraded.
🔵Meme Mode supports BNBCHAIN and Base.
You can upgrade your #TokenPocket via Google Play, App Store, or the official website.
🔗https://tokenpocket.pro
🆕 SOON is now live on TokenPocket.
SOON is a high-performance SVM Rollup designed to realize the Super Adoption Stack.
💙How to create/import a SOON wallet on #TokenPocket?
Guide👉https://help.tokenpocket.pro/en/wallet-operation/how-to-create-a-wallet/soon
🎈Discover the SOON SVM Ecosystem with Your TokenPocket!
👉https://tokenpocket.pro
2024: Moving Forward with Our Users, In Tune with the Market! 🌊
Thank you for all the support in 2024! Let’s continue growing stronger together with TokenPocket!💙
Dive into the #TokenPocket 2024 Annual Report ⤵️
https://tokenpocket-gm.medium.com/f01689f88a91
🔵New Bridge Integration on the #TokenPocket Trade page: SwapKit
🎯 Redefining Cross-Chain Bridging with TokenPocket!
SwapKit delivers an innovative cross-chain bridging solution, fully integrated into TokenPocket, making it easier than ever to swap cross-chain between Native $BTC, $USDT, $USDC, $ETH, and other leading chains and trending tokens.
Make cross-chain bridging easier than ever.
📱https://tokenpocket.pro
💻https://swap.transit.finance/?locale=en&market=1&inputChain=BTC&inputSymbol=BTC&outputChain=ETH&outputSymbol=ETH#/
🆕We released TokenPocket's new version on Android. 🔺2.4.0🔺
🔵 Support Swap & Bridge on the SuiNetwork.
🔵 Support SuiNetwork cold wallet and watch-only wallet features.
🔵 Support custom network sorting functionality.
🔵 Optimize the Transfer page.
🔵 Optimize users’ experience.
You can upgrade your #TokenPocket via Google Play or the official website.
🔗https://tokenpocket.pro