正則表達式 -- 提取並替換 ${} 之間的內容


一、提取 ${} 之間的內容

  1、正則表達式

  

 

  2、用 Python的正則 提取

  

   

 

 

二、替換 ${}  之間的內容

  1、替換

  

 

  2、封裝成專門的替換函數

import re


def my_split(resource_data: str, split_content: dict):
    """
    :param resource_data: 被替換的原數據
    :param split_content: 需要替換的內容
    """
    matches = re.findall(r"(?<=\$\{).*?(?=\})", resource_data)  # 提取需要替換的目標

    new_data = None  # 替換后的數據
    for i in matches:  # 替換過程
        new_value = split_content[i]
        if i == matches[0]:
            new_data = resource_data.replace("${" + i + "}", str(new_value))
        else:
            new_data = new_data.replace("${" + i + "}", str(new_value))
    return new_data


# 開始調試
old_data = '{"access-token": "${token}", "data": ${user_id}, "phone_code": ${code}}'
spilt_data = {"token": "123asf6549qewA+-*asd", "user_id": [1, 2, 3, 4], "code": 1356}

new_data0 = my_split(old_data, spilt_data)
print(new_data0)  # {"access-token": "123asf6549qewA+-*asd", "data": [1, 2, 3, 4], "phone_code": 1356}
data_dict = eval(new_data0)
print(type(data_dict["access-token"]))  # <class 'str'>
print(type(data_dict["data"]))  # <class 'list'>
print(type(data_dict["phone_code"]))  # <class 'int'>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM