match groups: optional groups not accessible

Peter Hansen peter at engcorp.com
Fri Jun 10 19:03:41 CEST 2005


Peter Hansen wrote:
> 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.

Oops... from Duncan's reply and a reread I can see I missed the point 
entirely... I obviously thought you were expecting the "yes" to be in a 
group too.  Duh.

-Peter



More information about the Python-list mailing list