Detailed explanation of using regular expressions to match time in Python

巴扎黑
Release: 2017-08-18 13:30:49
Original
2730 people have browsed it

This article mainly introduces the accurate regular matching method of Python time, and compares and analyzes Python's regular matching skills for time formats in the form of examples. Friends in need can refer to it

The examples in this article describe Python time An accurate regular matching method. Share it with everyone for your reference, the details are as follows:

It is not easy to use regular expressions to accurately match time

Method 1:


>>> import re
>>> t = '19:10:48'
>>> m = re.match(r'(.*):(.*):(.*)', t)
>>> m.groups()
('19', '10', '48')
Copy after login

Method 2:


>>> t = '19:10:48'
>>> m = re.match(r'(\d{2}):(\d{2}):(\d{2})', t)
>>> m.groups()
('19', '10', '48')
Copy after login

For example, the above cannot match accurately. For example, 24:61:61 obviously does not meet the requirements. The exact matching of

hours (H), 0-23
minutes (M), 0-59
seconds (S), 0-59
hours is as follows: 0?[0- 9]|1[0-9]|2[0-3]
minutes of accurate matching is as follows: 0?[0-9]|[1-5][0-9]
seconds of accuracy The match is as follows: 0?[0-9]|[1-5][0-9]

The complete regular match is:


>>> t = '23:59:08'
>>> p = re.compile(r'^(0?[0-9]|1[0-9]|2[0-3]):(0?[0-9]|[1-5][0-9]):(0?[0-9]|[1-5][0-9])$')
>>> s = p.search(t)
>>> s.groups()
('23', '59', '08')
Copy after login

The above is the detailed content of Detailed explanation of using regular expressions to match time in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!