在 re.sub 方法中指定替换的函数 (Python) [英] Function to dictate the replacements in re.sub method (Python)
问题描述
尝试使用正则表达式对字符串进行替换.
Trying to use regex to perform substitutions on a string.
re.sub(regex, repl_func, content)
问题是,当我需要替换依赖于来自 regex
的匹配对象时,我不明白如何通过 repl_func
进行替换;即我将使用该匹配对象作为字典键来获取需要替换该特定对象的匹配值.
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':
...
我尝试迭代所有匹配的对象,如上所示,但无法弄清楚如何应用 re.sub.如果我理解正确,我的第一个代码段中的 repl_function
需要以某种方式知道哪个是来自该正则表达式的匹配对象.
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.
任何想法,尤其是使用代码,将不胜感激,因为我现在才刚刚开始使用 Python.
Any ideas, especially using code will be much appreciated cause I am only just now starting with Python.
推荐答案
re.sub()
函数将匹配的对象作为参数传递给 repl_function
并替换使用匹配的字符串从该函数返回结果.如果你想用字典中的特定字符串替换匹配的对象,你可以简单地使用一个函数来处理:
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)
这篇关于在 re.sub 方法中指定替换的函数 (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!