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 capturing groups instead of a list of tuple
?
Given:
>>> import re >>> text = "bob sue jon richard harry" >>> pat = re.compile('(?P<name>[a-z]+)\s+(?P<name2>[a-z]+)') >>> pat.findall(text) [('bob', 'sue'), ('jon', 'richard')]
Should instead give:
[{'name': 'bob', 'name2': 'sue'}, {'name': 'jon', 'name2': 'richard'}]
The re. findall() method returns a list of strings. Each string element is a matching substring of the string argument.
If the pattern has one capturing group, the findall() function returns a list of strings that match the group. If the pattern has multiple capturing groups, the findall() function returns the tuples of strings that match the groups.
>>> import re >>> s = "bob sue jon richard harry" >>> r = re.compile('(?P<name>[a-z]+)\s+(?P<name2>[a-z]+)') >>> [m.groupdict() for m in r.finditer(s)] [{'name2': 'sue', 'name': 'bob'}, {'name2': 'richard', 'name': 'jon'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With