Nested named regex groups: how to maintain the nested structure in match result?

A small example:

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")

produces:

('hellocat', 'hello', 'cat', None)
{'hello': 'hellocat', 'nested': 'hello', 'other': 'cat', 'world': None}

The regex match result returns a flat dictionary, rather than a dictionary of dictionaries that would correspond with the nested structure of the regex pattern. By this I mean:

{'hello': {'nested': 'hello', 'other': 'cat'}, 'world': None}

Is there a “built-in” (i.e. something involving details of what is provided by the re module) way to access the match result that does preserve the nesting structure of the regex? By this I mean that the following are not solutions in the context of this question:

  • parsing the regex pattern myself to determine nested groups
  • using a data structure that represents a regex pattern as a nested structure, and then implementing logic for that data structure to match against a string as if it were a “flat” regex pattern.

1

Since you don’t mind using implementation details of the re module (which are subject to undocumented future changes), what you want is then possible by overriding the hooks that are called when the parser enters and leaves a capture group.

Reading the source code of the Python implementation of re‘s parser we can find that it calls the opengroup method of the re._parser.State object when entering a capture group, and calls the closegroup method when leaving.

We can therefore patch State with an additional attribute of a stack of dicts representing the sub-tree of the current group, override opengroup and closegroup to build the sub-trees when entering and leaving groups, and provide a method nestedgroupdict to fill the leaves (which have empty sub-trees) with actual matching values from the output of the groupdict method of a match:

import re

class State(re._parser.State):
    def __init__(self):
        super().__init__()
        self.treestack = [{}]

    def opengroup(self, name=None):
        self.treestack[-1][name] = subtree = {}
        self.treestack.append(subtree)
        return super().opengroup(name)

    def closegroup(self, gid, p):
        self.treestack.pop()
        super().closegroup(gid, p)

    def nestedgroupdict(self, groupdict, _tree=None):
        if _tree is None:
            _tree, = self.treestack
        result = {}
        for name, subtree in _tree.items():
            if subtree:
                result[name] = self.nestedgroupdict(groupdict, subtree)
            else:
                result[name] = groupdict[name]
        return result

re._parser.State = State

so that the parser will produce a state with treestack containing a structure of the named groups:

parsed = re._parser.parse(
    r"(?P<hello>(?P<nested>hello)?(?P<other>cat)?)?(?P<world>world)?"
)
print(parsed.state.treestack)

which outputs:

[{'hello': {'nested': {}, 'other': {}}, 'world': {}}]

We can then compile the parsed pattern to match it against a string and call groupdict to get the group-value mapping to feed into our nestedgroupdict method of the state to produce the desired nested structure:

groupdict = re._compiler.compile(parsed).match("hellocat world").groupdict()
print(parsed.state.nestedgroupdict(groupdict))

which outputs:

{'hello': {'nested': 'hello', 'other': 'cat'}, 'world': None}

Demo here

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật