Вы можете передать функцию repl
при вызове функции re.sub
. Функция принимает один аргумент объекта сопоставления и возвращает строку замены. Функция repl
вызывается для каждого неперекрывающегося вхождения шаблона.
Попробуйте это:
count = 0
def count_repl(mobj): # --> mobj is of type re.Match
global count
count += 1 # --> count the substitutions
return "your_replacement_string" # --> return the replacement string
text = "The original text" # --> source string
new_text = re.sub(r"pattern", repl=count_repl, string=text) # count and replace the matching occurrences in one pass.
ИЛИ,
Вы можете использовать re.subn , который выполняет ту же операцию, что и re.sub , но возвращает кортеж (new_string, number_of_subs_made).
new_text, count = re.sub(r"pattern", repl="replacement", string=text)
Пример:
count = 0
def count_repl(mobj):
global count
count += 1
return f"ID: {mobj.group(1)}"
text = "Jack 10, Lana 11, Tom 12, Arthur, Mark"
new_text = re.sub(r"(\d+)", repl=count_repl, string=text)
print(new_text)
print("Number of substitutions:", count)
Выход:
Jack ID: 10, Lana ID: 11, Tom ID: 12
Number of substitutions: 3