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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
Rod
  • 52,748
  • 3
  • 38
  • 55

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
  • 40,948
  • 31
  • 128
  • 181
  • 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
  • 222,467
  • 53
  • 283
  • 367
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
  • 75,757
  • 21
  • 156
  • 151
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
  • 96,106
  • 25
  • 196
  • 225