简体   繁体   中英

How to Search in file with sub-string contain backslash and \n

How do I search in a file for a sub-string containing a backslash?

substring="test\\123\\n"
filename="temp.txt"
file = open(filename, "r")
for line in file:
    if re.search(substring, line):

temp.txt

sometexttest\123\ntest
secoundline
...
etc

How to search string contain backslash and \\n like "test\\\\123\\\\n" .
I tried adding one more backslash but it is not working.

Is this what your looking for?

substring="test\\1234\\n"
filename="temp.txt"
file = open(filename, "r")

for line in file:
    if substring in line:
        print line

Giving the output:

sometexttest\1234\ntest

The re.search() call compiles your pattern and also interprets the backslashed expressions. Use re.escape() to prevent that:

if re.search(re.escape(substring), line):

Better still, don't use re.search() at all, you are looking for literal text here so a simple membership test should do:

if substring in line:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM