2017-08-16 102 views
1

我試圖讓我的正則表達式工作,但無法弄清楚我做錯了什麼。我試圖找到任何不是特定格式的文件。例如,所有文件都是以這種格式MM-DD-YY.pdf(例如05-13-17.pdf)的日期。我希望能夠找到任何不以該格式寫入的文件。Python - 正則表達式 - 匹配除

我可以創建一個正則表達式來找出那些具有:

(\d\d-\d\d-\d\d\.pdf) 

我使用負先行嘗試了它看起來是這樣的:

(?!\d\d-\d\d-\d\d\.pdf) 

,在沒有找到那些不再工作,但它不找不到不喜歡的文件。

我也嘗試在組後添加a。*,但後來發現整個列表。

(?!\d\d-\d\d-\d\d\.pdf).* 

我搜索過小的單子,現在來進行測試:

05-17-17.pdf Test.pdf 05-48-2017.pdf 03-14-17.pdf 

有沒有辦法來完成我正在尋找?

謝謝!

+0

如果您的輸入字符串是'05-17-17.pdf Test.pdf 05-48-2017.pdf 03-14-17.pdf',那麼您希望輸出的字符串是什麼? – Ajax1234

+0

我希望的輸出是'Test.pdf 05-48-2017.pdf'。它應該找到第二個日期,因爲它被寫爲2017年而不是17年。 – JakeIC

+0

@JakelC請看我最近的編輯。 – Ajax1234

回答

1

你可以試試這個:

import re 
s = "Test.docx 04-05-2017.docx 04-04-17.pdf secondtest.pdf" 

new_data = re.findall("[a-zA-Z]+\.[a-zA-Z]+|\d{1,}-\d{1,}-\d{4}\.[a-zA-Z]+", s) 

輸出:

['Test.docx', '04-05-2017.docx', 'secondtest.pdf'] 
+1

這可能適用於一組特定的輸入,但「文件名由字母.pdf組成」與「文件名不包含日期」的要求不一樣 – khelwood

+0

@khelwood謝謝您指出。我會要求OP澄清。 – Ajax1234

+0

謝謝!這適用於這種情況。有時,還有其他類型的格式不正確,例如「Jan-14-17.pdf」或「03-14-17(2).pdf」,或者它被保存爲錯誤的文件類型,例如「07-12-17.docx」 。有什麼方法可以找到任何與正則表達式不匹配的東西,或者我需要不斷創建多個與|鍵? – JakeIC

0

首先找出所有的匹配,然後從列表中單獨刪除它們。 firstFindtheMatching方法首先發現使用re庫相匹配的名字:

def firstFindtheMatching(listoffiles): 
    """ 
    :listoffiles: list is the name of the files to check if they match a format 
    :final_string: any file that doesn't match the format 01-01-17.pdf (MM-DD-YY.pdf) is put in one str type output. (ALSO) I'm returning the listoffiles so in that you can see the whole output in one place but you really won't need that. 

    """ 
    import re 
    matchednames = re.findall("\d{1,2}-\d{1,2}-\d{1,2}\.pdf", listoffiles) 
    #connect all output in one string for simpler handling using sets 
    final_string = ' '.join(matchednames) 
    return(final_string, listoffiles) 

這裏是輸出:

('05-08-17.pdf 04-08-17.pdf 08-09-16.pdf', '05-08-17.pdf Test.pdf 04-08-17.pdf 08-09-16.pdf 08-09-2016.pdf some-all-letters.pdf') 
set(['08-09-2016.pdf', 'some-all-letters.pdf', 'Test.pdf']) 

我用下面的主,如果你想重新生成的結果。這樣做的好處是您可以爲firstFindtheMatching()添加更多正則表達式。它可以幫助你保持獨立。

def main(): 

    filenames= "05-08-17.pdf Test.pdf 04-08-17.pdf 08-09-16.pdf 08-09-2016.pdf some-all-letters.pdf" 
    [matchednames , alllist] = firstFindtheMatching(filenames) 
    print(matchednames, alllist) 
    notcommon = set(filenames.split()) - set(matchednames.split()) 
    print(notcommon) 




if __name__ == '__main__': 
    main()