python中的正则匹配re模块

import re


# target_str = '{"mobilephone": "${not_exited_tel}", "pwd": "1234567890123456789", "regname": "KeYou"}'
# 定义两个匹配
pattern = re.compile(r"\$\{not_exited_tel\}")
regname_pattern = re.compile(r"\$\{regname\}")

# 使用pattern去匹配
# match_obj = re.search(pattern, target_str)
# sun中的第一个参数为pattern,第二个参数为需要替换的值,第三个参数为原始字符串
# sub返回的是替换之后的字符串
# new_str = re.sub(pattern, "18912345678", target_str)
# print(new_str)


def not_exited_tel_replace(data):
    if re.search(pattern, data):
        data = re.sub(pattern, "18912345678", data)

    if re.search(regname_pattern, data):
        data = re.sub(regname_pattern, "apple", data)

    return data


if __name__ == '__main__':
    target_str1 = '{"mobilephone": "${not_exited_tel}", "pwd": "123456", "regname": "${regname}"}'
    target_str2 = '{"mobilephone": "${not_exited_tel6}", "pwd": "6789", "regname": "orange"}'
    target_str3 = '{"mobilephone": , "pwd": "1234567890123456789", "regname": "${regname}"}'
    print(not_exited_tel_replace(target_str1))
    print(not_exited_tel_replace(target_str2))
    print(not_exited_tel_replace(target_str3))

你可能感兴趣的:(python)