the buggy regex in Python

Yingjie Lan lanyjie at yahoo.com
Thu Nov 25 12:32:54 CET 2010


I know many experts will say I don't have understanding...but let me pay this up front as my tuition.

Here are some puzzling results I have got (I am using Python 3, I suppose similar results for python 2).

When I do the following, I got an exception:
>>> re.findall('(d*)*', 'adb')
>>> re.findall('((d)*)*', 'adb')

When I do this, I am fine but the result is wrong:
>>> re.findall('((.d.)*)*', 'adb')
[('', 'adb'), ('', '')]

Why is it wrong?

The first mactch of groups: 
('', 'adb') 
indicates the outer group ((.d.)*) captured
the empty string, while the inner group (.d.) 
captured 'adb', so the outer group must have
captured the empty string at the end of the 
provided string 'adb'.

Once we have matched the final empty string '',
there should be no more matches, but we got
another match ('', '')!!!

So, findall matched the empty string in
the end of the string twice!!!

Isn't this a bug?

Yingjie


      



More information about the Python-list mailing list