Iterate over group names in a regex match?

Brian D briandenzer at gmail.com
Tue Jan 19 13:01:44 EST 2010


On Jan 19, 11:51 am, Brian D <brianden... at gmail.com> wrote:
> On Jan 19, 11:28 am, Peter Otten <__pete... at web.de> wrote:
>
>
>
> > Brian D wrote:
> > > Here's a simple named group matching pattern:
>
> > >>>> s = "1,2,3"
> > >>>> p = re.compile(r"(?P<one>\d),(?P<two>\d),(?P<three>\d)")
> > >>>> m = re.match(p, s)
> > >>>> m
> > > <_sre.SRE_Match object at 0x011BE610>
> > >>>> print m.groups()
> > > ('1', '2', '3')
>
> > > Is it possible to call the group names, so that I can iterate over
> > > them?
>
> > > The result I'm looking for would be:
>
> > > ('one', 'two', 'three')
> > >>> s = "1,2,3"
> > >>> p = re.compile(r"(?P<one>\d),(?P<two>\d),(?P<three>\d)")
> > >>> m = re.match(p, s)
> > >>> dir(m)
>
> > ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict',
> > 'groups', 'span', 'start']>>> m.groupdict().keys()
>
> > ['one', 'three', 'two']>>> sorted(m.groupdict(), key=m.span)
>
> > ['one', 'two', 'three']
>
> > Peter
>
> groupdict() does it. I've never seen it used before. Very cool!
>
> Thank you all for taking time to answer the question.


FYI, here's an example of the working result ...

>>> for k, v in m.groupdict().iteritems():
	k, v


('one', '1')
('three', '3')
('two', '2')


The use for this is that I'm pulling data from a flat text file using
regex, and storing values in a dictionary that will be used to update
a database.




More information about the Python-list mailing list