2016-06-09 54 views
1

使用Python在一個文件中匹配的字符串我想找到這個格式相匹配的文件中的字符串YYYY-MM-DD發現使用Python

Here is how my sample file looks like 
I want to find date 2016-01-01 ,2016-01-05 
then I want to find 2016-01-17 
then I want to find this date 2016-01-04 

輸出應該是

2016-01-01 
2016-01-05 
2016-01-17 
2016-01-04 
下面

是我目前使用的代碼,但我找不到匹配的記錄,對此的任何幫助將不勝感激?

#!/usr/bin/python 
import sys 
import csv 
import re 
pattern = re.compile("^([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9])$") 
for i, line in enumerate(open('C:\\Work\\scripts\\logs\\CSI.txt')): 
    for match in re.finditer(pattern, line): 
     print 'Found on line' % (i+1, match.groups()) 
+1

用'\ b'替換''','$'即'r'\ b \ d {4} - \ d {2} - \ d {2} \ b'' –

+0

它仍然無法正常工作/ – user1570210

+0

#在/ usr/bin中/ Python的 進口SYS 導入CSV 進口重新 模式= re.compile(R」! \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ')): for re.finditer(pattern,line)中的匹配: print'Found on line'%(i + 1,match.groups()) – user1570210

回答

0

我會刪除^($和,因爲你的日期似乎並不分隔:

re.compile("[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]") 
0

您可以使用正則表達式和日期時間從字符串

import re 
from datetime import datetime 
string = "I want to find date 2016-01-01 ,2016-01-05" 
pattern = re.complie("[\d]{4}-\d{2}-\d{2}") 
raw_dates = pattern.findall(string) 
parsed_dates = [] 
for date in raw_dates: 
    try: 
     d = datetime.strptime(date, "%Y-%m-%d") 
     parsed_dates.append(d) 
    except: 
     pass 
print(parsed_dates) 

得到有效日期輸出:

['2016-01-01', '2016-01-05']