[英]How to Search in file with sub-string contain backslash and \n
如何在文件中搜索包含反斜杠的子字符串?
substring="test\\123\\n"
filename="temp.txt"
file = open(filename, "r")
for line in file:
if re.search(substring, line):
臨時文件
sometexttest\123\ntest
secoundline
...
etc
如何搜索包含反斜杠和\\n
字符串,例如"test\\\\123\\\\n"
。
我嘗試再添加一個反斜杠,但是它不起作用。
這是您要找的東西嗎?
substring="test\\1234\\n"
filename="temp.txt"
file = open(filename, "r")
for line in file:
if substring in line:
print line
提供輸出:
sometexttest\1234\ntest
re.search()
調用將編譯您的模式, 並解釋反斜杠表達式。 使用re.escape()
可以防止這種情況:
if re.search(re.escape(substring), line):
更好的是,根本不使用re.search()
,您在這里查找文字文本,因此簡單的成員資格測試應該可以:
if substring in line:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.