2010-03-02 70 views

回答

2

也許你應該更清楚地提出你的問題,就像你想要做的一樣。也就是說,你可以將文件整理成一個整個字符串,並使用re匹配你的模式。

import re 
data=open("file").read() 
pat=re.compile("^.*pattern.*$",re.M|re.DOTALL) 
print pat.findall(data) 

有沒有更好的方法來做你想做的,不管它是什麼,沒有。

+0

因爲。*是貪婪的,只會在文件中找到'pattern'的一個實例。由於您指定了re.M標誌,所以$在文件中的每一個換行符之前匹配,所以使用greedy。*和re.DOTALL時,第一個。*將匹配文件中最後一個「模式」之前的所有內容,第二個將會匹配匹配最後一個'模式'後的所有內容。無論如何, – 2010-03-02 12:44:49

+1

。這不是一個完整的解決方案,因爲我們不確定OP真正想做什麼。我能做的最好的就是告訴他他可以將整個文件作爲字符串讀取,並像正常字符串一樣對其執行正則表達式。 – ghostdog74 2010-03-02 12:55:07

10

將整個文件讀入一個字符串,然後\ A只匹配字符串的開頭,而\ Z只匹配字符串的結尾。使用re.MULTILINE,'^'匹配換行符後面的字符串的開頭,'$'匹配換行符前面的字符串的末尾。請參閱re syntax的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) 

輸出:

['sentence one.', 'sentence two.', 'sentence three.', 'sentence four.'] 
['sentence one.'] 
['sentence four.'] 
相關問題