match groups: optional groups not accessible

Michael Chermside mcherm at mcherm.com
Fri Jun 10 15:38:46 EDT 2005


David Reitter writes:
> Why does the following result in an IndexError?
     [...]
> >>> import re
> >>> m = re.match('(?P<m>maybe)?yes', "yes")
> >>> m.group(1)
> >>> m.group('maybe')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> IndexError: no such group

Because the name of the named group in your example is 'm' not 'maybe'. 'maybe'
is the text to match. Try it like this:

>>> import re
>>> m = re.match('(?P<m>maybe)?yes', "yes")
>>> print m.group(1)
None
>>> print m.group('m')
None

-- Michael Chermside




More information about the Python-list mailing list