从字符串中提取日期

2024-10-04 09:20:19 发布

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

我想用Python编写一个正则表达式,从下面的字符串中提取'1994年6月28日',并将june转换为6:

fur = "missed intake office visit on 28 june 1994 at sierra vista nursing homesuicidal behavior hx of suicidal be"

我试过:

fur.extract(r'(?P<day>\d?\d)\s(?P<month>\W+)\s(?P<year>\d+)')

六月可以有多种形式,包括:“六月”、“六月”、“六月”、“六月;”等等


Tags: 字符串onvisitatsierraofficevistaintake
3条回答

你可以试试这个:

import re

fur = "missed intake office visit on 28 june 1994 at sierra vista nursing homesuicidal behavior hx of suicidal be"

data = re.search("(?P<day>\d{1,})\s(?P<month>[a-zA-Z]+)\s(?P<year>\d{4})", fur)
print(data.groupdict())

输出:

{'month': 'june', 'day': '28', 'year': '1994'}

您可以使用以下正则表达式:

(\d{2})[\s]([a-zA-Z]+)[\s](\d{4})

这将产生三组输出:

第一天:就是这一天

第二个:是月份名称

第三个:是年份

输出为:

Full match  30-42   `28 june 1994`
Group 1.    30-32   `28`
Group 2.    33-37   `june`
Group 3.    38-42   `1994`

你只需要在六月份或其他月份换衣服?如果你只需要在六月改变,我想这已经足够了

re.sub("\d{1,}\sjun[\,e\;]?\s\d{4}","6",yourstring)

相关问题 更多 >