Iterate over group names in a regex match?
Alf P. Steinbach
alfps at start.no
Tue Jan 19 12:28:20 EST 2010
* Brian D:
> 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')
I never used that beast (I'm in a sense pretty new to Python, although starting
some months back I only investigate what's needed for my writings), but checking
things in the interpreter:
>>> import re
>>> re
<module 're' from 'C:\Program Files\cpython\python26\lib\re.pyc'>
>>> 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 0x01319F70>
>>> m.groups()
('1', '2', '3')
>>> type( m.groups() )
<type 'tuple'>
>>> dir( m )
['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups',
'span', 'start']
>>> m.groupdict
<built-in method groupdict of _sre.SRE_Match object at 0x01319F70>
>>> m.groupdict()
{'one': '1', 'three': '3', 'two': '2'}
>>> print( tuple( m.groupdict().keys() ) )
('one', 'three', 'two')
>>> _
Cheers & hth.,
- Alf
More information about the Python-list
mailing list