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

+3


source to share


3 answers


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

.

+2


source


\\n

is not a newline character, it is an escaped backslash with n.



>>> import re
>>> a = '''\n5
... 8'''
>>> a=re.findall('\\n[0-9]',a)
>>> print(a)
['\n5', '\n8']

      

+2


source


because not \\n5

valid for newline, it will print\n5

+1


source







All Articles