![](/img/trans.png)
[英]General Python regex to extract dates (d,m,y) in different formats
[英]Using Python and Regex to extract different formats of dates
我有以下代码来匹配日期
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'), ('', '', '')]
请在此处查看regex
的链接。
您遇到的问题是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 模式的所有非重叠匹配上产生MatchObject
实例。
你可以试试这个正则表达式
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()
输出将是
23-SEP-2015
23-09-2015
23-09-15
2015年9月23日
试试这个
# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.