2015-03-31 89 views
0

我在python中使用以下代碼來搜索文件中的正則表達式,但它一直返回'None'。不明白它有什麼問題。 (編輯 - 添加完整的代碼)從Python中的文件搜索和打印正則表達式

def process_syslog(file_path): 
    with open(file_path, "r") as f: 

     for line in f: 
      link_down_match = re.search(r'Link Down on en0. (.*$)', line) 
      print en0_down_match.group() 

link_down_match,總是版畫 '無'。我正在做以下行的RE匹配:

要匹配的字符串:鏈接在en0上。原因1(未指定)。

基本上我搜索該文件包含與「原因」是在某些情況下(1-10)

這是我正在呼叫從主(片段)的函數

不同上述多個這樣的線
if current_file == 'syslog': 
       curr_file_path = dir_path + str(current_file) 
       process_syslog(curr_file_path) 

這裏有什麼問題?從文件我處理

段:

Mar 25 06:33:34 ethernet: Status: Link Down on en0. Reason 1 (Unspecified). 
Mar 25 06:34:07 ethernet: Status: Link Down on en1. Reason 4 (Unspecified). 
Mar 25 06:43:06 ethernet: Status: Link Down on en1. Reason 4 (Unspecified). 
Mar 25 06:44:16 ethernet: Status: Link Down on en1. Reason 4 (Unspecified). 
Mar 25 06:53:59 ethernet: Status: Link Down on en0. Reason 1 (Unspecified). 
Mar 25 06:53:59 ethernet: Status: Link Down on en1. Reason 8 (Unspecified. 
Mar 25 16:17:36 ethernet: Status: Link Down on en0. Reason 1 (Unspecified). 

回答

2

更新答案刪除舊的內容:

import re 

def process_syslog(file_path): 
    with open(file_path, "r") as f: 
     for line in f: 
      link_down_match = re.search(r'Link Down on en0. (\w+) (\d+)', line) 
      if link_down_match == None: 
       continue 
      print link_down_match.group() 

def main(): 
    process_syslog("syslog.txt") 

if __name__ == '__main__': 
    main() 

電流輸出:

Link Down on en0. Reason 1

Link Down on en0. Reason 1

Link Down on en0. Reason 1

+0

爲什麼我需要使用分裂線,如果我需要的只是分組提取。我期望在上面的代碼中提取group1:Reason和group2:1.然後在link_down_match中存儲此值之後,我應該可以在'if'語句中使用它,例如:if link_down_match =='1':做些什麼 – 2015-03-31 14:49:54

+0

好,那麼你可以在你的問題中添加'current_syslog'的內容。我只有一行參考,我認爲它是一個文件的內容,每行有類似的數據... – 2015-03-31 14:51:34

+0

剛編輯的代碼。基本上我正在搜索的文件包含上面提到的多個這樣的行,在某些情況下(1-10) – 2015-03-31 15:03:44

0

變化group()groups()

print link_down_match.groups() 

或者

print link_down_match.group(1) 
print link_down_match.group(2) 
print link_down_match.group(n) 
+0

不,它不需要改變'groups()'.'group'就好了。問題與'current_syslog'相關聯。 – vks 2015-03-31 04:41:34

0

幾件事情。

  • 雖然你沒有提到它,我想你在for循環之前有'with open ...'語句嗎?

  • 你確定你有總是正好在(\ w +)和(\ d +)之前的1個空格嗎?

  • 您在示例中用顏色打印了示例文本。我想這是從Stackoverflow的東西?否則在你的日誌中可能會有轉義序列。

我測試了r.e.在你的例子中,它運行在這裏,所以檢查上面...

+0

我編輯了上面的代碼並添加了更多信息。它應該回答你的問題。我也懷疑我將文件傳遞給函數的方式不正確,但不確定 – 2015-03-31 16:09:50

相關問題