簡體   English   中英

Python / Regex-如何使用正則表達式從文件名中提取日期?

[英]Python/Regex - How to extract date from filename using regular expression?

我需要使用python從文件名中提取日期。 日期采用以下格式:

month-day-year.somefileextension

例子:

10-12-2011.zip
somedatabase-10-04-2011.sql.tar.gz

提取此內容的最佳方法是使用正則表達式?

我有一些代碼:

import re
m = re.search('(?<=-)\w+', 'derer-10-12-2001.zip')
print m.group(0)

該代碼將打印“ 10”。 關於如何打印日期的一些線索?

最好的祝福,

假定日期始終采用以下格式:[MM]-[DD]-[YYYY]。

re.search("([0-9]{2}\-[0-9]{2}\-[0-9]{4})", fileName)

您要使用捕獲組

m = re.search('\b(\d{2}-\d{2}-\d{4})\.', 'derer-10-12-2001.zip')
print m.group(1)

應該打印10-12-2001

您可以擺脫更簡潔的正則表達式,但要確保它以-開頭,再以a開頭. 提供了一些最小的保護,以防止使用時髦的文件名或根本不匹配的文件名格式不正確的雙重匹配。

編輯:我替換了首字母-\\b ,它匹配字母數字和非字母數字之間的任何邊界。 這樣,它將匹配在日期之前是否存在連字符或字符串的開頭。

我認為您可以使用re.split提取日期,如下所示

$ ipython

In [1]: import re

In [2]: input_file = '10-12-2011.zip'

In [3]: file_split = re.split('(\d{2}-\d{2}-\d{4})', input_file, 1)

In [4]: file_split
Out[4]: ['', '10-12-2011', '.zip']

In [5]: file_split[1]
Out[5]: '10-12-2011'

In [6]: input_file = 'somedatabase-10-04-2011.sql.tar.gz'

In [7]: file_split = re.split('(\d{2}-\d{2}-\d{4})', input_file, 1)

In [8]: file_split
Out[8]: ['somedatabase-', '10-04-2011', '.sql.tar.gz']

In [9]: file_split[1]
Out[9]: '10-04-2011'

我使用Python 3.6.6,IPython 5.3.0運行了測試

**This is simple method to find date from text file in python**
import os
import re
file='rain.txt' #name of the file
if(os.path.isfile(file)): #cheak if file exists or not
    with open(file,'r') as i:
        for j in i: #we will travarse line by line in file 
            try:
                match=re.search(r'\d{2}-\d{2}-\d{4}',j) #regular expression for date
                print(match.group()) #print date if match is found
            except AttributeError: 
                pass
else:
    print("file does not exist")

好吧,您輸入的\\w+會在連字符后匹配一個或多個單詞字符,因此這是預期的結果。 您想要做的是在兩邊使用環顧四周,匹配第一個連字符和句點之間出現的數字和連字符:

re.search(r'(?<=-)[\\d-]+(?=\\.)', name).group(0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM