Mask multiple sensitive data using re.sub?

半城伤御伤魂 提交于 2021-02-11 15:16:42

问题


I would like to mask several values ​​in a string. This call works for a single value as expected.

message = "my password=secure and my private_key=securekey should not be logged."
message = re.sub(r"(?is)password=.+", "password=xxxx", str(message))

What does the regular expression have to look like so that I can mask multiple values from a dictionary?

d = {"password": "xxxx", "private_key": "zzzz"}
message = re.sub(r"(?is)\w=.+", lambda m: d.get(m.group(), m.group()), message)

Is it also possible to replace values with other values in the same regular expression call?

message = re.sub(r"data_to_mask", "xzxzxzx", str(message))

回答1:


you could do:

message = "my password=secure and my private_key=securekey should not be logged."

import re
d = {"password": "xxxx", "private_key": "zzzz"}

def replace(x):
    key = x.group(1)
    val = d.get(key, x.group(2))
    return f"{key}={val}"

re.sub(r"\b(\w+)=(\w+)", replace, message)
my password=xxxx and my private_key=zzzz should not be logged.


来源:https://stackoverflow.com/questions/63268086/mask-multiple-sensitive-data-using-re-sub

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!