Mar*_*nen 14
将整个文件读入字符串,然后\ A仅匹配字符串的开头,\ Z仅匹配字符串的结尾.使用re.MULTILINE,'^'匹配字符串的开头和刚刚在换行符之后,'$'匹配字符串的结尾并且在换行符之前.有关re语法,请参阅Python文档.
import re
data = '''sentence one.
sentence two.
a bad sentence
sentence three.
sentence four.'''
# find lines ending in a period
print re.findall(r'^.*\.$',data,re.MULTILINE)
# match if the first line ends in a period
print re.findall(r'\A^.*\.$',data,re.MULTILINE)
# match if the last line ends in a period.
print re.findall(r'^.*\.$\Z',data,re.MULTILINE)
Run Code Online (Sandbox Code Playgroud)
输出:
['sentence one.', 'sentence two.', 'sentence three.', 'sentence four.']
['sentence one.']
['sentence four.']
Run Code Online (Sandbox Code Playgroud)
也许你应该更清楚地提出你的问题,比如你想要做什么。也就是说,您可以将文件合并为一个完整的字符串,并使用 re 匹配您的模式。
import re
data=open("file").read()
pat=re.compile("^.*pattern.*$",re.M|re.DOTALL)
print pat.findall(data)
Run Code Online (Sandbox Code Playgroud)
有更好的方法可以做你想做的事,无论它是什么,而无需重复。