使用 Python 有选择地编辑 URL 中的可变长度密钥



我需要使用 Python 从 URL 字符串中编辑可变长度键。除密钥的最后四个字符外,所有字符都将被编辑。密钥的最后四个字符有意保持未编辑状态,以便进行识别。密钥的字符集是 ASCII 字母数字。否则,URL 必须不受影响。用于密文((的字符是unicodedata.lookup("FULL BLOCK")

示例输入:https://example.com/data?bar=irish&key=dc3e966e4c57effb0cc7137dec7d39ac.

示例输出:https://example.com/data?bar=irish&key=████████████████████████████39ac.

我正在使用Python 3.8。存在一个不同的问题,涉及在URL中的不同位置编辑密码,这对我没有帮助。

我尝试了一个简单的正则表达式替换,但它仅适用于固定长度的键,而我有一个可变长度的键。

实现此目的的一种灵活方法是使用带有替换函数的正则表达式替换。正则表达式使用不匹配的正后看断言和前瞻断言。

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'

最新更新