问题
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