在Python中使用正则表达式(regex)从字符串中提取不同格式的日期,可以通过以下步骤实现:
import re
pattern = r"\d{4}-\d{2}-\d{2}"
pattern = r"\d{2}/\d{2}/\d{4}"
pattern = r"\d{2}-\d{2}-\d{4}"
string = "Today is 2022-01-01, tomorrow is 01/02/2022, and yesterday was 01-01-2022."
dates = re.findall(pattern, string)
for date in dates:
print(date)
完整代码示例:
import re
string = "Today is 2022-01-01, tomorrow is 01/02/2022, and yesterday was 01-01-2022."
# YYYY-MM-DD
pattern = r"\d{4}-\d{2}-\d{2}"
dates = re.findall(pattern, string)
print("YYYY-MM-DD:")
for date in dates:
print(date)
# MM/DD/YYYY
pattern = r"\d{2}/\d{2}/\d{4}"
dates = re.findall(pattern, string)
print("MM/DD/YYYY:")
for date in dates:
print(date)
# DD-MM-YYYY
pattern = r"\d{2}-\d{2}-\d{4}"
dates = re.findall(pattern, string)
print("DD-MM-YYYY:")
for date in dates:
print(date)
这样,就可以从字符串中提取不同格式的日期了。
云+社区沙龙online第5期[架构演进]
企业创新在线学堂
云+社区技术沙龙[第7期]
云+社区技术沙龙[第15期]
新知·音视频技术公开课
云+社区技术沙龙[第27期]
Elastic 中国开发者大会
领取专属 10元无门槛券
手把手带您无忧上云