Skip to content Skip to sidebar Skip to footer

Why Is The Return Value Of An Empty Python Regexp Search A Match?

When passing an empty string to a regular expression object, the result of a search is a match object an not None. Should it be None since there is nothing to match? import re m =

Solution 1:

Empty pattern matches any part of the string.

Check this:

import re

re.search("", "ffff")
<_sre.SRE_Match object at 0xb7166410>

re.search("", "ffff").start()
0

re.search("$", "ffff").start()
4

Adding $ doesn't yield the same result. Match is at the end, because it is the only place it can be.

Solution 2:

Look at it this way: Everything you searched for was matched, therefore the search was successful and you get a match object.

Solution 3:

What you need to be doing is not checking if m is None, rather you want to check if m is True:

if m:
    print"Found a match"else:
    print"No match"

Also, the empty pattern matches the whole string.

Solution 4:

Those regular expressions are successfully matching 0 literal characters.

All strings can be thought of as containing an infinite number of empty strings between the characters:

'Foo' = '' + '' + ... + 'F' + '' + ... + '' + 'oo' + '' + ...

Post a Comment for "Why Is The Return Value Of An Empty Python Regexp Search A Match?"