Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Using re.match(), re returns a MatchObject on which the function .group('toto') can be used... 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 any simple way to do that? I can't find it anywhere...

like image 879
Thomas Leonard Avatar asked Nov 27 '12 13:11

Thomas Leonard


People also ask

Is it possible to name groups in Findall?

In order to handle groups in larger more complicated regexes, you can name groups, but those names are only accessible when you do a re.search pr re.match. From what I have read, findall has a fixed indices for groups returned in the tuple, The question is anyone know how those indices could be modified.

What is the syntax of re Findall in Python?

Syntax – re.findall () The syntax of re.findall () function is. re.findall(pattern, string, flags=0) where. Parameter. Description. pattern. [Mandatory] The pattern which has to be found in the string. string.

What is the result of the Findall() function?

The result of the findall () function depends on the pattern: If the pattern has no capturing groups, the findall () function returns a list of strings that match the whole pattern. If the pattern has one capturing group, the findall () function returns a list of strings that match the group.

Is the Findall () parameter required for regex matching?

This parameter is required. Before starting examples with the re.findall () regex matching examples lets list some popular and useful regex characters and patterns with the findall () method. . ? In the following example we will use to find and match alphabet and numbers with the specified regex.


1 Answers

You can't do that 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)]

This prints:

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

So we loop over each match yielded by .finditer() and take it's .groupdict() result.

like image 139
Martijn Pieters Avatar answered Oct 02 '22 09:10

Martijn Pieters