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'
添加回答
舉報