Функция 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
📢Peercoin Now is Available for Trade on SLEX!🎉
🔗Dear SLEXians, we're excited to inform you that Peercoin is now officially available for trading on the SLEX Centralized Exchange's spot market!
🔹Coin: Peercoin (PPC)
🔹TradingPair: PPC/USDC
🚀Join SLEX Centralized Exchange, deposit and start trading Peercoin on spot market!
#SLEXUpdate#PeercoinTrading#SpotMarket#SLEXTrading#PeercoinOnSLEX
Email | Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🎉 Syscoin (SYS) is now available on the SLEX Exchange! 🌟
🚀 Exciting news for all SLEXians: coin of the innovative blockchain platform Syscoin (SYS/USDT) is officially up for trading! This is a special listing because SLEX Exchange supports Syscoin UTXO, Syscoin Rollux, and Syscoin NEVM networks for spot market trading!
🔹Crypto: Syscoin
🔹Trading Pair: SYS/USDT
📈 Dive into trading Syscoin, enhance your portfolio, and boost your earnings with Syscoin (SYS\USDT) on the spot market at SLEX Centralized Exchange.
#SLEXUpdate#SYSUSDTTrading#SpotMarket#SLEXTrading#SYSUSDTOnSLEX
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🎉 Memecoin (MEME) is Listed on SLEX Exchange! 🌟
🚀 Big announcement for the SLEXians: the much-anticipated mem-token, MEME/USDT, is now available for trading on the SLEX Exchange!
🔹Crypto: Memecoin
🔹TradingPair: MEME/USDT
📈 Buy, diversify your portfolio, and trade Memecoin (MEME\USDT) on the spot market on the SLEX Centralized Exchange.
#SLEXUpdate#MEMEUSDTTrading#SpotMarket#SLEXTrading#MEMEUSDTOnSLEX
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
📢 Shiba Inu is Now Available for Trading on SLEX! 🌟
🐕 Exciting news for SLEXians: trading pair of famous mem-token, SHIB/USDT, is now live on the SLEX Exchange. This opens up the opportunity for users to trade Shiba Inu in the spot market or leverage it for various long-term investment strategies.
🔹Crypto: Shiba Inu
🔹TradingPair: SHIB/USDT
🚀 Seize the opportunity to successfully trade SHIB/USDT after Elon Mask twits and boost your earnings on the SLEX Centralized Exchange.
#SLEXUpdate#SHIBUSDTTrading#SpotMarket#SLEXTrading#SHIBUSDTOnSLEX
Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
📢 Chainlink is Now Available for Trading on SLEX! 🌟
🔗 Great news for the SLEX Community! We are excited to inform you that the LINK/USDT trading pair is now available on SLEX Exchange. Users have the opportunity to trade Chainlink on the spot market or use it as part of a variety of long-term investment strategies.
🔹Token: Chainlink
🔹TradingPair: LINK/USDT
🚀Embrace the chance to trade LINK/USDT on the SLEX Centralized Exchange. Deposit now and begin your trading journey with this dynamic pair in the spot market.
#SLEXUpdate#LINKUSDTTrading#SpotMarket#SLEXTrading#LINKUSDTOnSLEX
Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
📢 Nelore Coin isNow Tradable on SLEX!🎉
🔗Attention SLEX Community, we're excited to share that Nelore Coin has been officially listed and is now open for trading on the SLEX, either for spot market trading or as part of your long-term investment strategy!
🔹Coin: Nelore Coin (NLC)
🔹TradingPair: NLC/USDT
🚀Join the SLEX Centralized Exchange today, make your deposits, and start trading Nelore Coin in the spot market!
#SLEXUpdate#NeloreCoinTrading#SpotMarket#SLEXTrading#NeloreCoinOnSLEX
Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
📢LanaCoin is Now Available to Trade on SLEX!🎉
🔗Dear SLEXians, we're thrilled to announce that LanaCoin has been officially listed and is now available for spot market trading or long-term strategies investment on the SLEX Centralized Exchange!
🔥
🔹Coin: LanaCoin (LANA)
🔹Trading Pair: LANA/USDT
🚀Join the SLEX Centralized Exchange, deposit, and start your LanaCoin trading on the spot market!
#SLEXUpdate#LanaCoinTrading#SpotMarket#SLEXTrading#LanaCoinOnSLEX
Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🎉 Zcash (ZEC) is Now Listed on SLEX Exchange!🌟
🚀 Exciting news for all SLEXians: the highly sought-after cryptocurrency, Zcash (ZEC), is officially available for trading on the SLEX Exchange with two dynamic pairs!
🔹Crypto: Zcash;
🔹TradingPairs: ZEC/USDT & ZEC/BTC;
📈 Engage in trading, enhance your portfolio, and explore the possibilities with Zcash (ZEC\USDT & ZEC\BTC) in the spot market on SLEX Centralized Exchange.
#SLEXUpdate#ZECUSDTTrading#ZECBTCTrading#SpotMarket#SLEXTrading#ZECOnSLEX
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🌐 New Popular Cryptocurrencies Now Live on SLEX Exchange! 🎉
🚀 SLEX has expanded our trading offerings with the addition of Injective (INJ), Arbitrum (ARB), and Gala (GALA)!
🔹 Cryptos Listed:
- Injective (INJ)
- Arbitrum (ARB)
- Gala (GALA)
🔹 Trading Pairs:
- INJ/USDT
- ARB/USDT
- GALA/USDT
🤑Trade these dynamic assets to boost your earnings and diversify your portfolio on the SLEX Centralized Exchange!
#SLEXUpdate#INJUSDT#ARBUSDT#GALAUSDT#SpotMarket#SLEXTrading#TradeOnSLEX
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🌐Exciting New Crypto Listings on SLEX Exchange! 🚀
🎉Big news for traders! SLEX Exchange has broadened our horizons by including a diverse range of new cryptocurrencies in our trading portfolio.
🔹 Newly Listed Cryptos:
- BEAM (Beam)
- FIL (Filecoin)
- SNX (Synthetix)
- DYDX (dYdX)
- FET (Fetch)
- IMX (Immutable X)
- PEPE (PepeCoin)
- AMP (Amp)
- BLUR (Blur)
- SAND (The Sandbox)
💰Dive into trading new promising assets to amplify your earnings and broaden your investment portfolio on the SLEX Centralized Exchange!
#SLEXUpdate#PEPE#BLUR#AMP#SAND#IMX#FET#DYDX#SNX#FIL#BEAM#DiverseTrading#SLEXTrading
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter