2015-08-24 21 views
0

匹配的正則表達式我寫了下面的代碼在Python匹配內部文件的字符串:
的Python:在文件

#!/usr/bin/python 

import re 

f = open('file','r') 
for line in f: 
    mat = re.search(r'This',line) 
    mat.group(0) 
f.close() 

我用下面的文件作爲輸入:

This is the first line 
That was the first line 

但是,當我嘗試搜索表達式This它導致None輸出。 爲什麼不是字符串不匹配?

+0

@stribizhev你不需要那樣。另外你不打印'.group(0)' – muddyfish

回答

1

您應該使用with語法來確保文件已正確打開。

您沒有檢查是否有匹配,所以它會檢查第二行時崩潰。這裏有一些工作代碼:

import re 

with open('file','r') as f: 
    for line in f: 
     mat = re.search(r'This',line) 
     if mat: 
      print mat.group(0) 
+0

的結果打開文件的兩種方式有什麼區別? – sarthak

+0

@sarthak在這種情況下,您不需要關閉文件描述符 – Harman

+0

@sarthak如果引發異常,它也會關閉文件。它通常被認爲更好。另請參閱http://stackoverflow.com/questions/1369526/what-is-the-python-keyword-with-used-for – muddyfish

1

我更喜歡事先編譯模式,並在每次迭代中使用它。

import re 

pat = re.compile(r'This') 

with open('file') as f: 
    for line in f: 
     mat = pat.search(line) 
     if mat: 
      print(mat.group(0))