1 回答
TA贡献1818条经验 获得超7个赞
一种灵活的方法是使用带有替换函数的正则表达式替换。正则表达式使用不匹配的正向后向和前向断言。
import re
import unicodedata
_REGEX = re.compile(r"(?<=\Wkey=)(?P<redacted>\w+)(?=\w{4})")
_REPL_CHAR = unicodedata.lookup("FULL BLOCK")
def redact_key(url: str) -> str:
# Ref: https://stackoverflow.com/a/59971629/
return _REGEX.sub(lambda match: len(match.groupdict()["redacted"]) * _REPL_CHAR, url)
测试:
redact_key('https://example.com/data?bar=irish&key=dc3e966e4c57effb0cc7137dec7d39ac')
'https://example.com/data?bar=irish&key=████████████████████████████39ac'
>>> redact_key('https://example.com/data?key=dc3e966e4c57effb0cc7137dec7d39ac')
'https://example.com/data?key=████████████████████████████39ac'
>>> redact_key('https://example.com/data?bar=irish&key=dc3e966e4c57effb0cc7137dec7d39ac&baz=qux')
'https://example.com/data?bar=irish&key=████████████████████████████39ac&baz=qux'
>>> redact_key('https://example.com/data?bar=irish&baz=qux')
'https://example.com/data?bar=irish&baz=qux'
添加回答
举报