正则嵌套命名分组:如何在匹配结果中保留嵌套结构?
Python re模块是否支持内置生成嵌套分组结构的匹配字典?
问题背景
示例代码:
import re pattern = re.compile( r"(?P<hello>(?P<nested>hello)?(?P<other>cat)?)?(?P<world>world)?" ) result = pattern.match("hellocat world") print(result.groups()) print(result.groupdict() if result else "NO RESULT")
运行后输出:
('hellocat', 'hello', 'cat', None) {'hello': 'hellocat', 'nested': 'hello', 'other': 'cat', 'world': None}
期望得到的嵌套结构匹配结果:
{'hello': {'nested': 'hello', 'other': 'cat'}, 'world': None}
结论
Python标准库的re模块没有内置功能可以直接生成保留正则嵌套分组结构的匹配结果字典。
补充说明
re模块的命名分组捕获逻辑是扁平化设计的:无论分组嵌套多少层,所有命名分组都会被直接放入顶层的groupdict()返回值中,不会自动根据正则的嵌套关系组织成层级字典。
题目中排除的「自行解析正则模式确定嵌套分组」「自定义嵌套数据结构并实现匹配逻辑」,是目前实现嵌套结构结果的仅可行方向,但不符合本次问题的限制条件。因此仅依靠re模块内置能力,无法得到期望的嵌套结构结果。
内容的提问来源于stack exchange,提问作者bzm3r
相关产品推荐
相关产品推荐

