$
matches in two possible positions: (scroll to the section "Strings Ending with a Line Break")
- at the end of the input string and
- at the position before the last linebreak in a string if the string ends with a linebreak.
So if your string ends with one or more newlines, you get two matches for $
. In other cases, you get one.
If you only want to match the very end of a string, use \z
instead.
An experiment in Python:
>>> [match.start() for match in re.finditer("$", "hello")]
[5]
>>> [match.start() for match in re.finditer("$", "hello\n")]
[5, 6]
>>> [match.start() for match in re.finditer("$", "hello\n\n")]
[6, 7]
>>> [match.start() for match in re.finditer("$", "hello\n\n\n")]
[7, 8]