Regex 重新使用dict中的替换文本
re.sub中的替换文本能否从字典中检索值 以与其他SO相同的精神,使用代码Regex 重新使用dict中的替换文本,regex,python-3.x,Regex,Python 3.x,re.sub中的替换文本能否从字典中检索值 以与其他SO相同的精神,使用代码 coord_re = re.sub(r"(\d), (\d)", r"\1,\2", coords) 我还想在替换字符串中使用反向引用,但我想使用被称为\1、\2的字符串作为键,从某个字典中获取值 例如,我想要类似的东西: d = {...somedict} coord_re = re.sub(r"(\d), (\d)", d[value of \1]+','+d[value of \2], coords) 您可以
coord_re = re.sub(r"(\d), (\d)", r"\1,\2", coords)
我还想在替换字符串中使用反向引用,但我想使用被称为\1、\2的字符串作为键,从某个字典中获取值
例如,我想要类似的东西:
d = {...somedict}
coord_re = re.sub(r"(\d), (\d)", d[value of \1]+','+d[value of \2], coords)
您可以使用
lambda
或re.sub
中的函数:
import re
d = {
'1': 'a',
'2': 'b'
}
print( re.sub('(\d), (\d)', lambda g: d[g.group(1)] + ', ' + d[g.group(2)], '1, 2') )
印刷品:
a, b
从:
如果repl是一个函数,则会为每个非重叠函数调用它
模式的出现。该函数接受单个匹配对象
参数,并返回替换字符串。例如:
re.sub(pattern, repl, string, count=0, flags=0)