Monday, July 25, 2016

python正则表达式匹配含有时间的文件

import os
import re
files=os.listdir(os.getcwd())
for file in files:
    if re.search(r'\d{4}-\d{2}-\d{2}',file)!=None:
        if re.search(r'\d{4}-\d{2}-\d{2}',file).group(0)>='2016-07-01':
            print file
            print 'hah'
        else:
            pass
       
    else:
        pass


文件中含有
888888dddd2016-07-01hoho.txt
2016-06-29.txt
两个文件

扩展 匹配时间

有这么三种类型都是合法的
1,YYYY-MM-DD
2,YYYY-MM-DDTHH:mm:ss
3,  YYYY-MM-DDTHH:mm:SS.sss

import re
print re.search(r'\d{4}-\d{2}-\d{2}''xxxx1990-12-20xxxx').group(0)
print re.search(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}''xxxx2005-06-04T18:37:11xxxx').group(0)
print re.search(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}''xxxx2005-06-04T18:37:11.111xxxx').group(0)
 
pattern=re.compile(r'(\d{4}-\d{2}-\d{2})((T\d{2}:\d{2}:\d{2}|))((.\d{3})|)')
print pattern.search('xxxx2005-06-04T18:37:11.111xxxx').group(0)

No comments:

Post a Comment