Can't search for '\\ n' using regular expressions in python3
>>> import re
>>> a='''\\n5
... 8'''
>>> b=re.findall('\\n[0-9]',a)
>>> print(b)
['\n8']
Why is he showing \n8
instead \n5
? I used \
before \n
for the first time. I find using raw string
in regex in python a bit confusing. To me this doesn't seem to make any difference to the result
source to share
This is because newlines are considered the only character in strings.
When you execute \\n5
, you avoid \
to literally print \n5
, not a newline by Python standards.
When looking for a regex like \\n[0-9]
although in the first one \
you are avoiding the \n
regex expression , so at the end you are looking for \n
which is a Python newline. This matches the actual string of the string in your string, but not \\n
, which is two separate characters, escaped \
and n
.
source to share