我显然很不擅长正则表达式,它对我来说毫无意义...
我想要一个用于在字符串中匹配时间的表达式,例如01:23:45
。
我尝试了这个:
(r'(([0-9]*2)[:])*2([0-9]*2)
但是它没有起作用。我需要能够获取整个时间戳。其他一些我尝试过的仅找到了其中的两位数字。
很抱歉,您的中继器设置不正确:
r'\d{2}:\d{2}:\d{2}'
最小和最大数字的正确语法是 {n,m}
,或者精确匹配使用{n}
。字符类\d
比[0-9]
更易于使用;对于正则(非Unicode)匹配来说,它表示相同的含义。
为什么要使用正则表达式-使用适当的日期时间函数,可以免费获得验证,并且更易于理解...
from datetime import datetime
time = datetime.strptime('01:23:45', '%H:%M:%S').time()
print time.hour, time.minute, time.second
# 1 23 45
低效时间:
>>> datetime.strptime('99:45:63', '%H:%M:%S')
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
datetime.strptime('99:45:63', '%H:%M:%S')
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '99:45:63' does not match format '%H:%M:%S'
strptime
之前,需要先提取出来,就像排序一样。 - Martijn Pieters{2}
。[0-9]{2}
你应该使用{2}
而不是*2
。
[0-9]{2}:[0-9]{2}:[0-9]{2}
import re
timestamp_regex = r'(2[0-3]|[01][0-9]|[0-9]):([0-5][0-9]|[0-9]):([0-5][0-9]|[0-9])'
print(bool(re.match(timestamp_regex, '01:23:45'))) # True
print(bool(re.match(timestamp_regex, '01:01:45'))) # True
print(bool(re.match(timestamp_regex, '01:01:01'))) # True
print(bool(re.match(timestamp_regex, '1:1:1'))) # True
print(bool(re.match(timestamp_regex, '25:1:1'))) # False
\d\d:\d\d:\d\d
更加直观易懂。 - Engineer\d{2}:\d{2}:\d{2}
比\d\d:\d\d:\d\d
更明显。 - Engineer{n,m}
结构。我并不是指“复杂的重复组”。我只是指当前情况,当您需要验证时间 (00:00:00
) 时。 - Engineer