Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the return value of an empty python regexp search a match?

Tags:

python

regex

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 = re.search("", "some text")
if m is None:
    print "Returned None"
else:
    print "Return a match"

Incidentally, using the special symbols ^ and $ yield the same result.

like image 643
Rod Avatar asked Dec 04 '22 10:12

Rod


1 Answers

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.

like image 133
gruszczy Avatar answered Dec 29 '22 00:12

gruszczy