利用正则表达式,完成参数的替换

使用excel文件设计测试用例数据时,通常会使用变量进行参数化,发送请求时,再将变量替换为实际需要的值,这是就需要用到正则表达式来进行替换了。

为了代码和测试数据分离,本博客代码分为两个类文件,一个是测试数据文件,文件名为get_data.py,代码如下:

class GetData:
    #医院ID
    hospital = 200023
    #患者ID
    patientId = 123456

 一个为正则表达式文件,文件名为do_regx.py,代码如下:

import re
from regx.get_data import GetData

class DoRegx:
    def do_regx(self,c):
        while re.search('${(.*?)}', c):
            key = re.search('${(.*?)}', c).group()
            value = re.search('${(.*?)}', c).group(1)
            c = c.replace(key, str(getattr(GetData, value)))
        return c

if __name__ == '__main__':
    c = '{"hospitalId":"${hospital}","patientId":"${patientId}","phoneNo":"13141140059","checkCode":"765487"}'
    result = DoRegx().do_regx(c)
    print(result)
原文地址:https://www.cnblogs.com/benben-wu/p/10180282.html