I used to think of
$ in regular expressions as matching the end of the string. I was wrong! It actually might do something more subtle than that, depending on what regex engine you're using. In my native Python's
[m]atches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline.
Note! The end of the string, or just before the newline at the end of the string.
In : my_regex = re.compile("foo$") In : my_regex.match("foo") Out: <_sre.SRE_Match object; span=(0, 3), match='foo'> In : my_regex.match("foo\n") Out: <_sre.SRE_Match object; span=(0, 3), match='foo'>
I guess I can see the motivation—we often want to use the newline character as a terminator of lines (by definition) or files (by sacred tradition), without wanting to think of
\n as really part of the content of interest—but the disjunctive behavior of
$ can be a source of treacherous bugs in the fingers of misinformed programmers!