正则表达式:(日期/时间)每个部分之间的相同项目



编写一个简单的正则表达式来查找字符串中的日期和时间。 当刺痛中有特定日期时,识别时间项目存在一个小问题。这是正则表达式:

TIME_REGEX = "([0-1][0-9]|2[0-3])[:-_]?([0-5][0-9])[:-_]?([0-5][0-9])"

问题是我需要接受时间值,数字之间没有任何内容,因此有两个"[:-_]?"部分。但是,即使两者彼此不同,正则表达式也会匹配。因此,这也将日期"2011-07-30"匹配为时间20:11:07。

我可以更改正则表达式,使数字之间的两个项目相同,以便它匹配"201107"和"20-11-07",而不是"2011-07"或"20:11-07"吗?

您可以将分隔符存储在组中并重复使用它:

TIME_REGEX = "([0-1][0-9]|2[0-3])(?P<sep>[:-_]?)([0-5][0-9])(?P=sep)([0-5][0-9])"

在这里,(?P<sep>...)将该组的内容存储在名称下sep,我们用(?P+<sep>).这样,两个项目必须始终相等。

例:

for test in ['201107', '20-11-07', '20-11:07']:
match = re.match(TIME_REGEX, test)
if match:
print test, match.group(1, 3, 4), "delimiter: '{}'".format(match.group('sep'))

收益 率:

201107 ('20', '11', '07') delimiter: ''
20-11-07 ('20', '11', '07') delimiter: '-'

我建议你将第一个中间字符匹配到一个组中,并使用这个组的结果来匹配第二个字符,如下所示。您只需要在最后检索正确的组:

import re
times = ['20-11-07', '2011-07', '20-1107', '201107', '20:11-07', '20-10:07', '20:11:07']
TIME_REGEX = r'([0-1][0-9]|2[0-3])([:-_]*)([0-5][0-9])(2)([0-5][0-9])'
for time in times:
m = re.search(TIME_REGEX, time)
if m:
print(time, "matches with following groups:", m.group(1), m.group(3), m.group(5))
else:
print(time, "does not match")
# 20-11-07 matches with following groups: 20 11 07
# 2011-07 does not match
# 20-1107 does not match
# 201107 matches with following groups: 20 11 07
# 20:11-07 does not match
# 20-10:07 does not match
# 20:11:07 matches with following groups: 20 11 07

最新更新