Seek clarity on regex with $ and \Z

Viewed 42

There is wee confusion between $ and \Z in regex. I understand the underlying concept, \Z matches the end of the string regardless of the multiline mode where as $ matches end of the string or just before "\n" in multiline mode.

import re
items = ['lovely', '1\dentist', '2 lonely', 'eden', 'fly\n', 'dent']

# res = [e for e in items if re.search(r'\Aden|ly\Z', e)]
t = re.compile(r"^den|ly$")
res = [e for e in items if  t.search(e)]
print(res)
res = ['lovely', '2 lonely', 'fly\n', 'dent']

Why am I matching "fly\n", It ends with "\n" so isn't it suppose to ignore it where as r"^den|ly\Z" get me the desired result.

1 Answers

Note the python documentation for the $ special character:

Matches the end of the string or just before the newline at the end of the string [emphasis added] […]

In "fly\n", the newline is at the end of the string, so '$' can match just before it. If instead the string were "fly\n\n", then the regex would fail.

Related