0

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))
user5580578
  • 1,134
  • 1
  • 12
  • 28
  • what exactly are you trying to achieve? display of information is controlled by the frontend. hence it is inbuit in the html tags rtc – Onyambu Aug 05 '20 at 15:10
  • @Onyambu I want to mask out some sensitive data from a string before the string gets written to a file – user5580578 Aug 05 '20 at 15:16

1 Answers1

0

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.
Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • Thanks for your reply. How do I have to adjust the regular expression if there are also values ​​with "-" like "api-key" instead of "private_key"? – user5580578 Aug 05 '20 at 15:45
  • @user5580578 use `(?<=\s)(\S+)=(\S+)` – Onyambu Aug 05 '20 at 15:50
  • Can I add the dictionary d as parameter of the replace method? – user5580578 Aug 05 '20 at 16:15
  • @user5580578 why would you want to do that? Just put the dictionary inside the function. Sorry If this answer does not fit your needs. But so far, tit attempts to answer the posted problem – Onyambu Aug 05 '20 at 16:17
  • The values of the dictionary can change depending on the Python module using this part as a library dependency – user5580578 Aug 05 '20 at 16:47
  • @user5580578 Well you could wrap the whole idea in a function, such that you just pass a message and a dictionary, and return the substituted message – Onyambu Aug 05 '20 at 16:50