使用 re.sub 屏蔽多个敏感数据? [英] Mask multiple sensitive data using re.sub?

查看:40
本文介绍了使用 re.sub 屏蔽多个敏感数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想屏蔽一个字符串中的几个值.此调用按预期适用于单个值.

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))

推荐答案

你可以:

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.

这篇关于使用 re.sub 屏蔽多个敏感数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆