I can\'t figure out how to match a string but not if it has a trailing newline character (\\n
), which seems automatically stripped:
import re
p
This is the defined behavior of $
, as can be read in the docs that @zvone linked to or even on https://regex101.com:
$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)
You can use an explicit negative lookahead to counter this behavior:
import re
print(re.match(r'^foobar(?!\n)$', 'foobar'))
# <_sre.SRE_Match object; span=(0, 6), match='foobar'>
print(re.match(r'^foobar(?!\n)$', 'foobar\n'))
# None
print(re.match(r'^foobar(?!\n)$', 'foobar\n\n'))
# None