使用正则表达式查找并替换查询字符串

时间:2020-07-23 18:28:01

标签: python regex

因此,我尝试检查查询字符串中的凭据,如果找到密码,则将密码替换为“ ak_redacted”。

示例字符串:

a=123&b=456&userName=abc&password=xyz&key=1&value=2

这应该变成:

a=123&b=456&userName=abc&password=ak_redacted&key=1&value=2

尝试使用以下代码段,但似乎不起作用

qs = request['querystring']
print(qs)
updatedqs = ''
if "password" in params:
  if "userName" in params:
    updatedqs = re.sub(r"/(?=((.*)password)=([^&]+)(.*)|).+/g", r"\1=ak_redacted\4", qs)
    print(updatedqs)

1 个答案:

答案 0 :(得分:1)

from urllib.parse import parse_qsl, urlencode

query_string = "a=123&b=456&userName=abc&password=xyz&key=1&value=2"
parsed_query = dict(parse_qsl(query_string))

if parsed_query.get("password"):
    parsed_query["password"] = "ak_redacted"

redacted_query_string = urlencode(parsed_query)

print(redacted_query_string)

输出:

a=123&b=456&userName=abc&password=ak_redacted&key=1&value=2