match groups: optional groups not accessible

david.reitter at gmail.com david.reitter at gmail.com
Fri Jun 10 07:36:50 EDT 2005


Why does the following result in an IndexError?
I try to match an optional group, and then access it via its group
name. The group happens to not participate in the match, but is
obviously defined in the pattern.
The documentation says that, at least for numbered groups, "If a group
is contained in a part of the pattern that did not match, the
corresponding result is None.".
So I would expect None rather than an IndexError, which is (only?)
supposed to occur "If a string argument is not used as a group name in
the pattern".

I would expect named groups and numbered groups to be behave the same
way.
Where's my mistake?

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

PS.: Please cc your reply to my e-mail address.




More information about the Python-list mailing list