且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python-将正则表达式匹配替换为匹配对值

更新时间:2022-11-14 19:54:35

当您具有一对一的映射关系时,请考虑使用字典两类数据,例如五位数代码和别名。然后,根据其代码即可轻松访问任何特定的别名:

Consider using a dictionary when you have a one-to-one mapping of two categories of data, such as five digit codes and aliases. Then it's easy to access any particular alias, given its code:

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!