首页 > 解决方案 > Python - 用匹配的对值替换正则表达式匹配

问题描述

假设我有一个与运行时可用的 5 位代码相关的别名列表:

aliasPairs = [(12345,'bob'),(23456,'jon'),(34567,'jack'),(45678,'jill'),(89012,'steph')]

我想找到一种简洁的表达方式:将行中的id替换为匹配的别名,例如:

line = "hey there 12345!"
line = re.sub('\d{5}', value in the aliasPairs which matches the ID, line)
print line

应该输出:

hey there bob!

Python 专业人士如何以简洁的方式编写枚举表达式?

谢谢和欢呼!

标签: pythonregexenumeration

解决方案


当您对两类数据(例如五位代码和别名)进行一对一映射时,请考虑使用字典。然后很容易访问任何特定的别名,给定它的代码:

import re

aliases = {
    "12345":"bob",
    "23456":"jon",
    "34567":"jack",
    "45678":"jill",
    "89012":"steph"
}

line = "hey there 12345!"
line = re.sub('\d{5}', lambda v: aliases[v.group()], line)
print(line)

结果:

hey there bob!

推荐阅读