2017-09-01 1491 views
1

我想從標準vsftp日誌文件中獲取整個文件名和擴展名。Python正則表達式匹配整個文件名包含文件擴展名

的文件是如下:

Wed Aug 31 10:23:59 2017 1 ::ffff:172.18.1.168 18593420 /Shell_Scripting.sh b _ i r user1 ftp 0 * c 
Wed Aug 31 10:24:18 2017 1 ::ffff:172.18.1.168 18593420 /test.txt b _ i r user1 ftp 0 * c 

我想正則表達式

pattern = re.compile(r'\/(\w+)') 
match = pattern.search(ftpfile) 
print match.group(1) 

但唯一的匹配文件名(Shell_Scripting &試驗)不包括擴展名(.SH & .TXT)。

我試圖re.compile(r'\/(.+\.\w+)')re.compile(r'\/(\w+\.\w+)')

他們都表現出AttributeError: 'NoneType' object has no attribute 'group'

什麼應該是正確的正則表達式匹配文件名包含文件擴展名?

+0

不要嘗試正則表達式匹配文件名。那麼空間呢?其他有趣的角色呢,都是由本地文件系統所允許的?怎麼樣多個'.ext.ens.ions'?取而代之的是將部件匹配到「18593420」,然後匹配一組'。+',然後匹配'b_i r user1 ftp 0 * c'-part。 – user2722968

+0

@ user2722968感謝提醒。是的,空白空間應該是一個問題。我會嘗試另一種方法 – Ilikeperl

回答

2

你可以使用一個列表理解一個簡單的正則表達式:

import re 

log = """ 
Wed Aug 31 10:23:59 2017 1 ::ffff:172.18.1.168 18593420 /Shell_Scripting.sh b _ i r user1 ftp 0 * c 
Wed Aug 31 10:24:18 2017 1 ::ffff:172.18.1.168 18593420 /test.txt b _ i r user1 ftp 0 * c 
""" 

rx = re.compile(r'/(\S+)') 
filenames = [match.group(1) for line in log.split("\n") for match in rx.finditer(line)] 
print(filenames) 
# ['Shell_Scripting.sh', 'test.txt'] 

心臟是/(\S+)部分,它尋找一個/,隨後在至少一個非空白字符。

+0

非常感謝。您的方法適用於大多數情況(多個擴展名,有趣的字符),不包括空格。我會繼續努力處理空白。謝謝你幫助我! – Ilikeperl

-1

如果只處理SHTXT文件,你可以這樣做:

pattern = re.compile(r'\/(\w+\.(?:txt|sh))') 
+0

編輯:這是對現在刪除的評論的迴應:afaik'\ w'將匹配一個下劃線/爲我做。 – patrick

1

您可以使用re.findall

import re 

s = ['Aug 31 10:23:59 2017 1 ::ffff:172.18.1.168 18593420 /Shell_Scripting.sh b _ i r user1 ftp 0 * c', 'Wed Aug 31 10:24:18 2017 1 ::ffff:172.18.1.168 18593420 /test.txt b _ i r user1 ftp 0 * c'] 

files = [re.findall("[a-zA-Z_]+\.\w+", i) for i in s] 

new_files = [i[0] for i in files if i] 

輸出:

['Shell_Scripting.sh', 'test.txt'] 
相關問題