You can pass a repl function while calling the re.sub function.
The function takes a single match object argument, and returns the replacement string. The repl function is called for every non-overlapping occurrence of pattern.
Try this:
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.
OR,
You can use re.subn which performs the same operation as re.sub, but return a tuple (new_string, number_of_subs_made).
new_text, count = re.sub(r"pattern", repl="replacement", string=text)
Example:
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)
Output:
Jack ID: 10, Lana ID: 11, Tom ID: 12
Number of substitutions: 3