[英]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.