Q:

How to avoid mutations when using the sub() method in regex?

namesRegex = re.compile(r"Agent \w+") 
namesRegex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')

When I do this, it doesnt only change Agent, but Alice and Bob also. I mean it changes one more word.
I tried to understand this, for example,  when i want to change only Alice, it also changes "gave" too.
How can I only change one word in Regex?
Also one question more, we write like this re.compile(r".* etc")
but even if we dont write "r", like r.compile(".* etc") it does the same thing. Then why do we write r letter over there?

A:

You can make 'Agent ' part of a positive lookbehind pattern instead so that re.sub only matches the agent's name and therefore substitutes only the agent's name with 'CENSORED':
namesRegex = re.compile(r"(?<=Agent )\w+") 

