简体   繁体   中英

Find and replace in query string using regex

So I am trying to check for credentials in the query string and replace the password with "ak_redacted", if one is found.

sample string:

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

This should become:

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

Trying to use the below snippet but it does not seem to work

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)
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)

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM