Skip to main content
 首页 » 编程设计

python之此日期需要正则表达式模式

2024年10月25日25linjiqin

我有类似的日期字符串

  Date: April 1st, 2015 
  Date: March 31st, 2015 
  Date: March 26th, 2015 

我需要提取适合 python 日期时间模式的日期。 我将 '%B %d %Y' 作为 python 日期时间模式。

那么我怎样才能将上面的字符串提取为日期时间格式。 正则表达式输出应该是:

March 31 2015 
August 1 2014 

请帮助我构建漂亮的正则表达式模式。

请您参考如下方法:

^.*?:\s*|[a-zA-Z]+, 

您可以为此使用 re.sub 并替换为 空字符串。参见演示。

https://regex101.com/r/sJ9gM7/42#python

import re 
p = re.compile(r'^.*?:\s*|[a-zA-Z]+,', re.MULTILINE | re.IGNORECASE) 
test_str = " Date: April 1st, 2015\n Date: March 31st, 2015\n Date: March 26th, 2015" 
subst = "" 
 
result = re.sub(p, subst, test_str)