0

I need some advice to get my regular expression working as expected. It is an extended question to this question.

I want to replace all passwords and keys with "xxxx" and "zzzz".

import re
d = {"password": "xxxx", "secret-key": "zzzz"}

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

message = "test&password=secure password=secure and my secret-key=securekey should not be logged."
re.sub(r"(?<=???)(\S+)=(\S+)", replace, message)

Any number of characters and special characters can be placed in front of the key. In my example above, 'test&' is in front of the key "password" that I am looking for. But it is also possible that the key you are looking for starts after a whitespace (e.g. password=secure).

In the end this should come out of the above example.

message = test&password=xxxx password=xxxx and my secret-key=zzzz should not be logged.
user5580578
  • 1,134
  • 1
  • 12
  • 28

1 Answers1

0

If "any number of characters and special characters can be placed in front of the key", then I think you'll be better off matching your keys explicitly. For example:

import re
d = {"password": "xxxx", "secret-key": "zzzz"}

message = "test&password=secure password=secure and my secret-key=securekey should not be logged."

for k, mask in d.items():
    message = re.sub(f'(?<={k}=)(\\S+)', mask, message)

print(message)

This will output:

test&password=xxxx password=xxxx and my secret-key=zzzz should not be logged.
larsks
  • 277,717
  • 41
  • 399
  • 399