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')
Method 2:
>>> t = '19:10:48' >>> m = re.match(r'(\d{2}):(\d{2}):(\d{2})', t) >>> m.groups() ('19', '10', '48')
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')
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!