带有换行符的Python正则表达式不';不匹配

带有换行符的Python正则表达式不';不匹配,python,regex,Python,Regex,我有一个包含 Line1 Line2 Line3 Line4 在我正在搜索的Python程序中 Line1 Line2 Line3 节目是 import re file = open("blah.log","r") file_contents = file.read() pattern='''Line1 Line2 Line3''' matchObj = re.search(pattern, file_contents, re.M|re.I) if matchObj: prin

我有一个包含

Line1
Line2
Line3
Line4
在我正在搜索的Python程序中

Line1
Line2
Line3
节目是

import re

file = open("blah.log","r")
file_contents = file.read()

pattern='''Line1
Line2 
Line3'''

matchObj = re.search(pattern, file_contents, re.M|re.I)
if matchObj:
   print matchObj.group(0)
else:
   print "No match!!"
但是,即使模式在文件中,也显示不匹配

但是如果

file_contents = '''Line1
Line2
Line3
Line4''' # not reading from the file 
现在它与正则表达式模式匹配

这是什么原因


如何使程序能够从文件中读取内容

由于文件中的行由
'\r\n'
分隔,因此您搜索的模式应该考虑到这一点

为方便起见,您仍然可以使用三重引号来初始化要搜索的字符串,但随后使用
str.replace()
方法将所有出现的
'\n'
替换为
'\r\n'

pattern='''Line1
Line2 
Line3'''.replace('\n', '\r\n')
此外,如果只需要子字符串匹配,则可以使用中的
操作符,而不是更昂贵的正则表达式匹配:

if pattern in file_contents:
   print pattern
else:
   print "No match!!"

由于文件中的行由
'\r\n'
分隔,因此您搜索的模式应该考虑到这一点

为方便起见,您仍然可以使用三重引号来初始化要搜索的字符串,但随后使用
str.replace()
方法将所有出现的
'\n'
替换为
'\r\n'

pattern='''Line1
Line2 
Line3'''.replace('\n', '\r\n')
此外,如果只需要子字符串匹配,则可以使用
中的
操作符,而不是更昂贵的正则表达式匹配:

if pattern in file_contents:
   print pattern
else:
   print "No match!!"

文件中的新行字符可以是'\n'、'\r'或'\r\n'。这取决于操作系统。为了安全起见,请尝试匹配所有新行字符

pattern='''Line1(\n|\r|\r\n)Line2(\n|\r|\r\n)Line3'''

文件中的新行字符可以是'\n'、'\r'或'\r\n'。这取决于操作系统。为了安全起见,请尝试匹配所有新行字符

pattern='''Line1(\n|\r|\r\n)Line2(\n|\r|\r\n)Line3'''

文件里到底是什么?你能发布一个十六进制转储文件吗?它在我的情况下有效。为什么要使用Python 2?我可以在调试模式中看到,文件内容是File1\r\nFile2\r\nFile3\r\nFile4,但模式包含File1\nFile2\nFile3@Prajwal我正要回答这个问题。这就是你的答案。那我不能用那种格式吗?比如三重引号?在这种情况下,正确的匹配方式是什么@B档案里到底有什么?你能发布一个十六进制转储文件吗?它在我的情况下有效。为什么要使用Python 2?我可以在调试模式中看到,文件内容是File1\r\nFile2\r\nFile3\r\nFile4,但模式包含File1\nFile2\nFile3@Prajwal我正要回答这个问题。这就是你的答案。那我不能用那种格式吗?比如三重引号?在这种情况下,正确的匹配方式是什么@伯兴