4

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.

Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
Rod
  • 48,232
  • 3
  • 34
  • 52

4 Answers4

12

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.

gruszczy
  • 39,180
  • 28
  • 124
  • 173
  • if no matches are found, what does it return? Some falsy value like `None` or does it throw an exception?! [nevermind, found my answer in the documentation.](https://docs.python.org/2/library/re.html#re.search) – oldboy Jul 18 '18 at 20:33
3

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

sth
  • 211,504
  • 50
  • 270
  • 362
1

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.

Rafe Kettler
  • 73,388
  • 19
  • 151
  • 149
1

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' + '' + ...
Cameron
  • 91,868
  • 20
  • 192
  • 220