{"title":"Python正则表达式匹配动态字段名:wsSettings, tlsSettings, grpcSettings等","description":"本文介绍如何使用Python正则表达式匹配字典中动态变化的字段名,例如wsSettings、tlsSettings、grpcSettings等,并提供通用代码示例。","keywords":"Python, 正则表达式, 字典, 字段名, 动态匹配, wsSettings, tlsSettings, grpcSettings","content":"{"network": "ws", "security": "none", "wsSettings": {"acceptProxyProtocol": false, "path": "/", "headers": {"Host": "ir.helma.ir"}} }" 里面"wsSettings",但是有可能它会变成"tlsSettings"和"grpcSettings",或者别的,给我一个通用匹配的内容:你可以使用正则表达式的|操作符来匹配多个可能的字段名,下面是一个通用的示例代码: \n\npython\nimport re\n\ndata = \{'network\': \'ws\', \'security\': \'none\', \'wsSettings\': \{'acceptProxyProtocol\': False, \'path\': \'/\', \'headers\': \{'Host\': \'ir.helma.ir\' }\} }\n\n# 定义可能的字段名\npossible_fields = [\'wsSettings\', \'tlsSettings\', \'grpcSettings\']\n\n# 构建正则表达式\npattern = r\'(({}))\' .format(\'|\'.join(possible_fields))\n\n# 使用正则表达式查找匹配的字段\nmatched_fields = re.findall(pattern, str(data))\n\n# 输出匹配到的字段\nprint(matched_fields)\n\n\n输出结果会是一个包含匹配到的字段名的列表,例如:[\'wsSettings\']。你可以根据需要进行进一步处理。


原文地址: https://www.cveoy.top/t/topic/pxzU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录