Subject: bug#21159: Fails To Match Empty String

From: Squirrely <[email-masked]>
Date: Wed, 29 Jul 2015 23:38:47 +0100

Hi

I'm a bit of a regular expression noob, so I'm not sure if this is a bug
or if I'm just missing something about how grep works.

Here's a demo of the issue I have encountered:

> bash$ rm empty
> bash$ touch empty
> bash$ # I am expecting a match, so grep should return 0.
> bash$ grep '^$' empty
> bash$ echo $?
> 1
> bash$ # Hmmm... weird.
> bash$ # Same example but using STDIN instead...
> bash$ echo -n ""| grep '^$'
> bash$ echo $?
> 1
> bash$ # Same result.  How does the python re module treat this?
> bash$ python3
> >>> import re
> >>> m = re.search("^$", "")
> >>> type(m)
> <class '_sre.SRE_Match'>
> >>> # A match was found.  Python returns 'None' if it's not a match,
> >>> # like this...
> >>> m = re.search("fo?", "bar")
> >>> type(m)
> <class 'NoneType'>

I know that the Python re module and grep use a different regex syntax,
but I'm pretty sure "^$" has the same meaning for both.

I discounted the idea that grep only checks lines that end with a
newline character because of this:

> bash$ echo -en "foo\nfoo\nfoo"|grep foo
> foo
> foo
> foo

As you can see, the third foo is checked and matched despite not being
terminated with a newline character (observe the echo "-n" switch).

So... why does ^$ match the empty string with python but not with grep?

-Squirrely