[Tutor] uncomprehension on RE

Stephen Nelson-Smith sanelson at gmail.com
Wed Sep 19 14:04:52 CEST 2007


On 9/19/07, cedric briner <work at infomaniak.ch> wrote:
> Hello,
>
> I do not understand the behaviour of this:
>
> import re
> re.search('(a)*','aaa').groups()
> ('a',)
>
> I was thinking that the ``*'' will operate on the group delimited by the
> parenthesis. And so, I was expecting this result:
> ('a', 'a', 'a')
>
> Is there something I'am missing ?

<reposting as sent to OP by default... I am sure the list used to
munge addresses and things were sent to the list by default>

What you are trying to do, I think, is get the * to expand to the
number of times you expect your group to appear.  You cannot do this.
You need to specify as many groups as you want to get returned:

re.search('(x)(x)(x)', 'xxx').groups()  would work.

In your case you have a single group that matches several times.
Python simply returns one match.

Consider this:

>>> re.search('(.)*', 'abc').groups()
('c',)

Can you see how that happens?

You could do re.findall('x', 'xxx') - but I don't know what you are
actually trying to do.

S.


More information about the Tutor mailing list