Функция 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
🏦ESMA призывает использовать стейблкоины, подчиняющиеся MiCA
🔹 Европейское управление по надзору за рынком ценных бумаг (ESMA) призвало криптокомпании использовать только те стейблкоины, которые соответствуют законодательству о цифровых активах (MiCA).
🔹 Под закон подпадают как валюты с фиатным обеспечением, так и токены, привязанные к другим активам. Компании, работающие в еврозоне, должны отказаться от использования нерегулируемых стейблкоинов.
🔹ESMA подчеркнула, что к 31 марта 2025 года все нерегулируемые стейблкоины должны покинуть рынок ЕС.
🔹 Крупнейший стейблкоин USDT, эмитентом которого является Tether, пока не имеет лицензии на работу в еврозоне. Инвесторы должны конвертировать такие токены в регулируемые цифровые активы.
🔹 Количество лицензированных криптокомпаний в ЕС растет. Платформа Crypto.com недавно объявила о выходе на рынок, отметив, что MiCA обеспечивает прозрачность и защиту инвесторов.
#ESMA#MiCA#Стейблкоины
🚀 ECB Supports ESMA Oversight of Major Cross-Border Financial Firms
The European Central Bank (ECB) has expressed its support for a European Commission proposal to grant the Paris-based European Securities and Markets Authority (ESMA) direct oversight of significant cross-border financial firms, including large crypto asset service providers. According to NS3.AI, this move marks a shift from the current Markets in Crypto-Assets (MiCA) framework, where national regulators are responsible for supervising crypto asset service providers (CASPs), while ESMA primarily plays a coordinating role. Although the ECB's opinion is non-binding, the proposal will now proceed to negotiations among EU member states and the European Parliament.
#ECB#ESMA#EuropeanCommission#CrossBorderFinance#CryptoAssets#MiCA#FinancialRegulation#EUParliament#CASPs
🚀 EU Proposes Regulatory Shift for Cross-Border Institutions
The European Union is considering a significant change in its regulatory framework for cross-border institutions. According to ChainCatcher, the proposal suggests transferring regulatory authority from national supervisory bodies to the European Securities and Markets Authority (ESMA). This shift would affect large Crypto Asset Service Providers (CASPs), trading venues, central counterparties, and central securities depositories.
This proposal marks the most substantial structural adjustment in the EU's crypto regulatory framework since the Markets in Crypto-Assets Regulation (MiCA) was fully implemented for CASPs at the end of 2024. Under the current MiCA framework, national authorities serve as the primary regulators, while ESMA plays a coordinating role.
#EU#regulatoryshift#crossborderinstitutions#ESMA#CryptoAssetServiceProviders#CASPs#MiCA#cryptoregulation#EUcrypto
🚀 European Central Bank Supports EU's Financial Regulatory Reform
The European Central Bank (ECB) has expressed its support for the European Commission's proposal to centralize financial regulation. According to Odaily, the plan aims to transfer the regulatory authority of cross-border financial institutions, including crypto asset service providers (CASPs), from national regulators to the European Securities and Markets Authority (ESMA). This move is intended to deepen the integration of the EU capital markets and enhance international competitiveness. The ECB emphasized the need for ESMA to be adequately staffed and funded, while minimizing market disruptions during the regulatory transition.
#EuropeanCentralBank#EU#FinancialRegulation#ECB#EuropeanCommission#ESMA#CryptoAssets#CapitalMarkets#InternationalCompetitiveness#CASPs#RegulatoryReform