match groups: optional groups not accessible

D

david.reitter

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?
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: no such group

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

Peter Hansen

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.

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
 
D

Duncan Booth

david.reitter said:
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".
That is exactly what does happen.
I would expect named groups and numbered groups to be behave the same
way.
Where's my mistake?
Using 'maybe' as a group name when the only group in the pattern is called
'm'.
 
P

Peter Hansen

Peter said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,835
Latest member
KetoRushACVBuy

Latest Threads

Top