簡體   English   中英

使用正則表達式在查詢字符串中查找和替換

[英]Find and replace in query string using 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)
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM