re.findall which returns a dict of named capturing groups?

后端 未结 4 1119
忘了有多久
忘了有多久 2020-12-04 15:12

Inspired by a now-deleted question; given a regex with named groups, is there a method like findall which returns a list of dict with the named cap

4条回答
  •  自闭症患者
    2020-12-04 16:11

    you could switch to finditer

    >>> import re
    >>> text = "bob sue jon richard harry"
    >>> pat = re.compile('(?P[a-z]+)\s+(?P[a-z]+)')
    >>> for m in pat.finditer(text):
    ...     print m.groupdict()
    ... 
    {'name2': 'sue', 'name': 'bob'}
    {'name2': 'richard', 'name': 'jon'}
    

提交回复
热议问题