Reputation:
Trying to use regex to perform substitutions on a string.
re.sub(regex, repl_func, content)
The problem is that I do not understand how the replacement will occur via the repl_func
when I need the substitution to be dependent on the matching object from that regex
; i.e. I will use that matched object as a dictionary key to get the matching value with which that particular object needs to be replaced.
for mobj in re.finditer(regex, content):
t = mobj.lastgroup
v = match_obj.group(t)
if t == 'NAME':
...
elif t == '\n':
...
I have tried to iterate all the matching objects, as seen above, but cannot figure out how to apply the re.sub. If I understand correctly, the repl_function
in my first code segment needs to somehow know which is the matched object from that regex.
Any ideas, especially using code will be much appreciated cause I am only just now starting with Python.
Upvotes: 2
Views: 1440
Reputation: 107347
The re.sub()
function passes the matched object to repl_function
as an argument and replaces the returned result from that function with the matched string. If you want to replace the matched object with a particular string in a dictionary you can simply use a function to handle that:
def repl_func(matched_obj):
my_dict = {'NAME':'rep1', '\n':'rep2'}
try:
match = matched_obj.group(0)
except AttributeError:
matched = ''
# Or raise an exception
else:
return my_dict.get(match, '')
re.sub(regex, repl_func, content)
Upvotes: 2
Reputation: 1433
The re
docs are pretty clear on this one:
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of
pattern
in string by the replacementrepl
.If
repl
is a function, it is called for every non-overlapping occurrence ofpattern
. The function takes a single match object argument, and returns the replacement string.
Upvotes: 1