使用Python和正则表达式提取不同格式的日期

5
我有以下代码来匹配日期
import re
date_reg_exp2 = re.compile(r'\d{2}([-/.])(\d{2}|[a-zA-Z]{3})\1(\d{4}|\d{2})|\w{3}\s\d{2}[,.]\s\d{4}')
matches_list = date_reg_exp2.findall("23-SEP-2015 and 23-09-2015 and 23-09-15 and Sep 23, 2015")
print matches_list

我期望的输出结果是:
["23-SEP-2015","23-09-2015","23-09-15","Sep 23, 2015"]

我理解的是:

我所获取的信息是:

[('-', 'SEP', '2015'), ('-', '09', '2015'), ('-', '09', '15'), ('', '', '')]

请点击这里查看有关正则表达式的信息。

1
我认为你的第一个(可能放错了位置 - 前两个数字没有被捕获,你告诉它要捕获的第一件事是[-/.]序列。 - Simon Fraser
2
实际上,对于正则表达式来说,这有点困难...在这种情况下,使用"23-SEP-2015 and 23-09-2015 and 23-09-15 and Sep 23, 2015".split(' and ')怎么样? - Remi Guan
在这种情况下它可以工作,但实际上输入字符串并没有用 and 分隔。它可能是 This string is 23-09-2015 and It can also be something。我需要一个匹配,写成 ['23-09-2015'] - Kartheek Palepu
@SimonFraser 我不擅长使用 正则表达式 如果你能帮我处理上述表达式,那就太好了。 - Kartheek Palepu
@PalepuKartheek,请看看我回答中的正则表达式。它将处理您想要提取日期的字符串。 - Rohan Amrute
3个回答

3
你的问题在于re.findall仅返回捕获文本,不包括第0组(整个匹配)。因为你需要整个匹配(第0组),所以只需使用re.finditer并获取group()值即可:
matches_list = [x.group() for x in date_reg_exp2.finditer("23-SEP-2015 and 23-09-2015 and 23-09-15 and Sep 23, 2015")]

请查看IDEONE演示

re.findall(pattern, string, flags=0)
返回字符串中与pattern匹配的所有不重叠的结果,以字符串列表形式返回... 如果模式中存在一个或多个组,则返回一个组列表;如果模式有多个组,则将返回一个元组列表。

re.finditer(pattern, string, flags=0)
返回一个迭代器,该迭代器在字符串中为RE pattern找到的所有不重叠的匹配项生成MatchObject实例。


2
你可以尝试使用这个正则表达式。
date_reg_exp2 = re.compile(r'(\d{2}(/|-|\.)\w{3}(/|-|\.)\d{4})|([a-zA-Z]{3}\s\d{2}(,|-|\.|,)?\s\d{4})|(\d{2}(/|-|\.)\d{2}(/|-|\.)\d+)')

接下来使用re.finditer()

for m in re.finditer(date_reg_exp2,"23-SEP-2015 and 23-09-2015 and 23-09-15 and Sep 23, 2015"):
print m.group()

输出将为:

2015年9月23日
2015年9月23日
15年9月23日
2015年9月23日


你的正则表达式还会匹配到我不需要的东西,比如 55.123.4567。此外,斜杠 / 会被解释为“未转义的正斜杠”,所以我猜你需要使用 \/ - Kartheek Palepu
我认为你的日期中没有出现 .,所以在正则表达式中不需要包含它。对于 /,你可以使用 \/ - Rohan Amrute
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Kartheek Palepu
我能想到的一些情况有:dd-mm-yyyydd/mm/yyyydd.mm.yyyydd-mon-yyyydd/mon/yyyydd.mon.yyyyMon dd, yyyyMon dd. yyyy - Kartheek Palepu

1
尝试这个。
# The first (\d{2}-([A-Z]{3}|\d{2})-(\d{4}|\d{2})) group tries to match the first three types of dates
# rest will match the last type
dates = "23-SEP-2015 and 23-09-2015 and 23-09-15 and Sep 23, 2015"
for x in re.finditer('((\d{2}-([A-Z]{3}|\d{2})-(\d{4}|\d{2}))|([a-zA-Z]{3}\s\d{1,2},\s\d{4}))', dates):
    print x.group(1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接