import re
# 解析字符串中全局变量并进行替换
def resolve_global_var(pre_resolve_var, global_var_dic, global_var_regex='\${.*?}',
match2key_sub_string_start_index=2, match2key_sub_string_end_index=-1):
'''
:param pre_resolve_var: 准备进行解析的变量<str>
:param global_var_dic: 全局变量字典<dict>
:param global_var_regex: 识别全局变量正则表达式<str>
:param match2key_sub_string_start_index: 全局变量表达式截取成全局变量字典key值字符串的开始索引<int>
:param match2key_sub_string_end_index: 全局变量表达式截取成全局变量字典key值字符串的结束索引<int>
:return: 解析后的变量<str>
'''
if not isinstance(pre_resolve_var, str):
raise TypeError('pre_resolve_var must be str!')
if not isinstance(global_var_dic, dict):
raise TypeError('global_var_dic must be dict!')
if not isinstance(global_var_regex, str):
raise TypeError('global_var_regex must be str!')
if not isinstance(match2key_sub_string_start_index, int):
raise TypeError('match2key_sub_string_start_index must be int!')
if not isinstance(match2key_sub_string_end_index, int):
raise TypeError('match2key_sub_string_end_index must be int!')
# re_global_var = re.compile(global_var_regex)
def global_var_repl(match_obj):
start_index = match2key_sub_string_start_index
end_index = match2key_sub_string_end_index
match_value = global_var_dic.get(match_obj.group()[start_index:end_index])
return match_value if match_value else match_obj.group()
resolved_var = re.sub(pattern=global_var_regex, string=pre_resolve_var, repl=global_var_repl)
return resolved_var
global_var_dic ={
"username":"xiaoming"
}
blist =[1,2,3]
alist = '{"name":"${username}","age":blist[1]}'
alist= resolve_global_var(alist,global_var_dic)
print(alist)
c = eval(alist)
print(c)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?