import re text = 'Special Agent Upsorn told Special Agent Awesome a secret' # replace the agent's name with ***AAAAA*** # find a match # replace that match with ????? regex = re.compile(r'Agent [A-Z][a-z]+') for match_obj in regex.finditer(text): print('match object --', match_obj.group()) string = regex.sub('?????', text) print('replace --', string) # grouping # agent_name_regex = re.compile(r"Agent (\w)\w*") # agent_name_regex = re.compile(r"Agent ([A-Z])[a-z]*") # agent_name_regex = re.compile(r"Agent ([A-Z])([a-z])[a-z]*") agent_name_regex = re.compile(r"(Agent )([A-Z])([a-z])[a-z]*") # make regex into 3 groups and use group 2 in replacement search_result = agent_name_regex.search(text) # return the first match object print(search_result.group(0), '=', search_result.group()) print('groups --', search_result.groups()) if search_result != None: # index starts from 1 for i in range(1, len(search_result.groups())+1): print('index', i, search_result.group(i)) # sub(pattern_to_replace, original_string) # for each match object, keep the 1st group, replace the remaining groups string = agent_name_regex.sub(r"\1?????", text) # replace with the 1st group followed by ????? print("1st group:", string) # for each match object, keep the 2nd group, replace the remaining groups string = agent_name_regex.sub(r"####\2?????", text) print("2nd group:", string)