简体   繁体   English

如何使用re.findall()使用符号组名

[英]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() ? 是否可以使用(?P<toto>...)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. 使用re.match() ,re返回一个MatchObject ,函数.group('toto')可以在其上使用...我想做一些接近的事情。

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... 我在任何地方找不到它......

You can't do that with .findall() . 你不能用.findall()做到这.findall() However, you can achieve the same effect with .finditer() and some list comprehension magic: 但是,您可以使用.finditer()和一些列表理解魔法获得相同的效果:

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. 所以我们遍历.finditer()产生的每个匹配,并取得它的.groupdict()结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM