How to use a symbolic group name using re.findall ()

Is it possible to access the name of a symbolic group defined in a regular expression using (?P<toto>...) with the equivalent of re.findall() ?

Using re.match() , re returns a MatchObject on which to use the .group('toto') function ... I would like to do something close.

Here is an example:

 import re my_str = 'toto=1, bip=xyz, toto=15, bip=abu' print re.findall('toto=(?P<toto>\d+)\,\sbip=(?P<bip>\w+)', my_str) 

It returns:

 [('1', 'xyz'), ('15', 'abu')] 

I would like to get something like:

 [{'toto':'1', 'bip':'xyz'}, {'toto':'15', 'bip':'abu'}] 

Is there an easy way to do this? I can’t find anything ...

+8
python regex match findall
source share
1 answer

You cannot do this with .findall() . However, you can achieve the same effect with .finditer() and some list comprehension magic:

 print [m.groupdict() for m in re.finditer('toto=(?P<toto>\d+)\,\sbip=(?P<bip>\w+)', my_str)] 

Fingerprints:

 [{'toto': '1', 'bip': 'xyz'}, {'toto': '15', 'bip': 'abu'}] 

So, we .finditer() over each match obtained by .finditer() , and get the result .groupdict() .

+9
source share

All Articles