match groups: optional groups not accessible

Peter Hansen peter at engcorp.com
Fri Jun 10 08:03:28 EDT 2005


david.reitter at gmail.com wrote:
> 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.
> 
>>>>m = re.match('(?P<m>maybe)?yes', "yes")

Uh, don't you need to actually *group* the first "yes" part, with 
parentheses, to make it a group?  Otherwise you aren't going to be 
treating it as other than text-between-groups-that-can-be-skipped.

-Peter



More information about the Python-list mailing list