如何使用正则表达式从该字符串中获取日期?

2024-04-27 04:23:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,看起来像这样:

<some_text> February 19, 2009 through March 17, 2009 <some_text>

如何使用正则表达式和python来提取日期。你知道吗

我试过这个来看看我是否至少能匹配字符串,但它没有找到任何东西:

r'\w*\d{1,2},\w+\d{4}\w+through\w+\d{1,2},\w+\d{4}'

任何帮助都将不胜感激。你知道吗


Tags: 字符串textsomemarchthroughfebruary
2条回答

怎么样:

(\w+ \d\d?, \d{4})\b.+?\b(\w+ \d\d?, \d{4})\b

你需要使用检索做这个。你知道吗

因为这将是一个很长的regexp,我建议您编译它,只是为了清楚起见。你知道吗

基本regexp如下所示:

date_finder = re.compile("(\w+) through (\w+)")

这将找到两个由'through'分隔的字符串。你知道吗

要访问它们,您将使用

out = data_finder.search(input_str)

out.group(1) # first paren match
out.group(2) # second paren match group

接下来,您必须检查您的组是否是日期字符串。你知道吗

date_finder = re.compile("([JFMASOND][a-z]+\s+\d{1,2}[\s,]+\d{4}) through")

可从以下位置访问:

out = date_finder.search(input_str)
out.group(1) # date string before through

要得到第二个,只需在“through”的另一边重复regexp。regexp可能会根据您的输入数据进行一些调整,但您应该了解这个想法。你知道吗

希望有帮助。你知道吗

相关问题 更多 >