python日期正则表达式
时间: 2024-04-02 15:29:56 浏览: 87
Python中可以使用正则表达式来匹配和处理日期。以下是一些常见的Python日期正则表达式示例:
1. 匹配YYYY-MM-DD格式的日期:
```python
import re
date_pattern = r"\d{4}-\d{2}-\d{2}"
date_string = "2022-01-01"
match = re.match(date_pattern, date_string)
if match:
print("日期格式正确")
else:
print("日期格式错误")
```
2. 匹配MM/DD/YYYY格式的日期:
```python
import re
date_pattern = r"\d{2}/\d{2}/\d{4}"
date_string = "01/01/2022"
match = re.match(date_pattern, date_string)
if match:
print("日期格式正确")
else:
print("日期格式错误")
```
3. 提取YYYY-MM-DD格式的日期:
```python
import re
date_pattern = r"(\d{4})-(\d{2})-(\d{2})"
date_string = "2022-01-01"
match = re.match(date_pattern, date_string)
if match:
year = match.group(1)
month = match.group(2)
day = match.group(3)
print(f"年份: {year}, 月份: {month}, 日份: {day}")
else:
print("日期格式错误")
```
阅读全文
相关推荐


















