Функция 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
#SAND/USDT analysis :
#SAND is currently in a downtrend, consistently making new lows on the daily time frame. The price is facing rejection from the resistance zone and the 200 EMA, and it is expected to test the support zone and the previous swing low. Look for a pullback to identify a potential short entry.
TF : 1D
Entry : $0.2852
Target : $0.2275
SL : $0.3253
#SAND/USDT analysis :
#SAND is currently in an uptrend, forming Higher Highs (HHs) and Higher Lows (HLs) above the 200ema. The price has broken the trendline after bouncing from a support zone. It is expected to maintain its bullish momentum and target previous highs.
TF : 30min
Entry : $0.2958
Target : $0.3076
SL : $0.2888
#SAND Market Analysis
SAND/USDT remains bearish with price hovering near the lower Bollinger Band and RSI sitting close to oversold at 33. MACD confirms downside momentum, reinforcing the weak structure below key resistances around 0.077. Bull case: hold above 0.0717 to target a retest of 0.0755 and possibly 0.0771 resistance. Bear case: lose 0.0717 and risk acceleration toward lower supports. Watch 0.0717 closely for the next directional cue.
---
➖➖➖➖➖➖➖
Bitcoin Bullets® Trading
#SAND Market Analysis
SAND/USDT is in a bearish trend with RSI deep in oversold territory and MACD confirming downside momentum. Price trades near the lower Bollinger Band, signaling potential for a short-term bounce but overall pressure remains. Bull case: hold above 0.0755 to target a retest of 0.0780 resistance. Bear case: break below 0.0755 risks continuation lower, exposing further downside below 0.071. Key level to watch: 0.0755 support.
---
➖➖➖➖➖➖➖
Bitcoin Bullets® Trading
#SAND Market Analysis
SAND/USDT shows a weak bullish structure with price hovering near the lower Bollinger Band and RSI sitting below 50, signaling limited upside momentum. MACD remains bearish, indicating sellers still have influence despite the mild uptrend. Bull case: hold above 0.0765 to target resistance at 0.0797 for a potential bounce. Bear case: lose 0.0755 and risk deeper pullback towards the next support zone. Key level to watch: 0.0765.
---
➖➖➖➖➖➖➖
Bitcoin Bullets® Trading