【问题标题】:re.sub using replacement text from dict [duplicate]re.sub 使用 dict 中的替换文本 [重复]
【发布时间】:2019-08-21 15:40:23
【问题描述】:

re.sub 中的替换文本可以从字典中检索值吗?

本着与另一个 SO 的 post 相同的精神,使用代码

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)

【问题讨论】:

    标签: regex python-3.x


    【解决方案1】:

    您可以使用lambdare.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
    

    来自documentation

    re.sub(pattern, repl, string, count=0, flags=0)
    

    如果 repl 是一个函数,它会在每个不重叠的地方调用 模式的发生。该函数采用单个匹配对象 参数,并返回替换字符串。例如:

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 2013-02-03
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      相关资源
      最近更新 更多