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...
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.
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.
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.
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.
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.
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