在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)
这样,就可以从字符串中提取不同格式的日期了。
领取专属 10元无门槛券
手把手带您无忧上云