Python正則表達式匹配日期與時間的方法
下面給大家介紹下Python正則表達式匹配日期與時間
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Randy' import re from datetime import datetime test_date = '他的生日是2016-12-12 14:34,是個可愛的小寶貝.二寶的生日是2016-12-21 11:34,好可愛的.' test_datetime = '他的生日是2016-12-12 14:34,是個可愛的小寶貝.二寶的生日是2016-12-21 11:34,好可愛的.' # date mat = re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_date) print mat.groups() # ('2016-12-12',) print mat.group(0) # 2016-12-12 date_all = re.findall(r"(\d{4}-\d{1,2}-\d{1,2})",test_date) for item in date_all: print item # 2016-12-12 # 2016-12-21 # datetime mat = re.search(r"(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2})",test_datetime) print mat.groups() # ('2016-12-12 14:34',) print mat.group(0) # 2016-12-12 14:34 date_all = re.findall(r"(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2})",test_datetime) for item in date_all: print item # 2016-12-12 14:34 # 2016-12-21 11:34 ## 有效時間 # 如這樣的日期2016-12-35也可以匹配到.測試如下. test_err_date = '如這樣的日期2016-12-35也可以匹配到.測試如下.' print re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_err_date).group(0) # 2016-12-35 # 可以加個判斷 def validate(date_text): try: if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'): raise ValueError return True except ValueError: # raise ValueError("錯誤是日期格式或日期,格式是年-月-日") return False print validate(re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_err_date).group(0)) # false # 其他格式匹配. 如2016-12-24與2016/12/24的日期格式. date_reg_exp = re.compile('\d{4}[-/]\d{2}[-/]\d{2}') test_str= """ 平安夜圣誕節(jié)2016-12-24的日子與去年2015/12/24的是有不同哦. """ # 根據(jù)正則查找所有日期并返回 matches_list=date_reg_exp.findall(test_str) # 列出并打印匹配的日期 for match in matches_list: print match # 2016-12-24 # 2015/12/24
https://www.pythonxyz.com/10025-python-regex-match-date-time.xyz
ps:下面看下python正則表達式中原生字符r的作用
r的作用
>>> mm = "c:\\a\\b\\c" >>> mm 'c:\\a\\b\\c' >>> print(mm) c:\a\b\c >>> re.match("c:\\\\",mm).group() 'c:\\' >>> ret = re.match("c:\\\\",mm).group() >>> print(ret) c:\ >>> ret = re.match("c:\\\\a",mm).group() >>> print(ret) c:\a >>> ret = re.match(r"c:\\a",mm).group() >>> print(ret) c:\a >>> ret = re.match(r"c:\a",mm).group() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'group' >>>
說明
Python中字符串前面加上 r 表示原生字符串
與大多數(shù)編程語言相同,正則表達式里使用"\"作為轉義字符,這就可能造成反斜杠困擾。假如你需要匹配文本中的字符"\",那么使用編程語言表示的正則表達式里將需要4個反斜杠"\\":前兩個和后兩個分別用于在編程語言里轉義成反斜杠,轉換成兩個反斜杠后再在正則表達式里轉義成一個反斜杠。
Python里的原生字符串很好地解決了這個問題,有了原生字符串,你再也不用擔心是不是漏寫了反斜杠,寫出來的表達式也更直觀。
>>> ret = re.match(r"c:\\a",mm).group() >>> print(ret) c:\a
總結
以上所述是小編給大家介紹的Python正則表達式匹配日期與時間的方法,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
相關文章
Python中使用jpype調用Jar包中的實現(xiàn)方法
這篇文章主要介紹了Python中使用jpype調用Jar包中的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12Python常見格式化字符串方法小結【百分號與format方法】
這篇文章主要介紹了Python常見格式化字符串方法,結合實例形式分析了百分號方法和format函數(shù)進行字符串格式化的具體使用技巧,需要的朋友可以參考下2016-09-09python3+selenium實現(xiàn)126郵箱登陸并發(fā)送郵件功能
這篇文章主要為大家詳細介紹了python3+selenium實現(xiàn)126郵箱登陸并發(fā)送郵件功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-01-01