帮我写一个获取字符串中的日期的正则
时间: 2024-01-29 12:01:59 浏览: 22
获取字符串中的日期,可以使用正则表达式。以下是一个示例正则表达式,可以匹配包含年月日的日期:
```python
import re
date_regex = r'\d{4}-\d{2}-\d{2}'
text = '这是一个包含日期2021-05-26的字符串'
match = re.search(date_regex, text)
if match:
print(match.group())
else:
print('未找到日期')
```
这个正则表达式可以匹配形如"2021-05-26"的日期格式。如果需要匹配其他日期格式,可以根据实际情况修改正则表达式。
相关问题
java获取字符串中的时间不使用正则
可以使用Java自带的日期时间类库来获取字符串中的时间,例如:
```java
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String input = "现在的时间是12:34:56";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime time = LocalTime.parse(input.substring(7), formatter);
System.out.println("提取到的时间为:" + time);
}
}
```
上述代码将字符串 `"现在的时间是12:34:56"` 中的时间部分提取出来,并转换为 `LocalTime` 类型。其中,`DateTimeFormatter` 是用来指定时间格式的,`LocalTime.parse()` 方法可以将字符串按照指定格式解析成时间类型。
获取字符串中的日期
您可以使用Python中的正则表达式来获取字符串中的日期。以下是一个示例代码:
```python
import re
text = "今天是2022年10月20日,明天是2022年10月21日。"
matches = re.findall(r"\d{4}年\d{1,2}月\d{1,2}日", text)
for match in matches:
print(match)
```
输出:
```
2022年10月20日
2022年10月21日
```
正则表达式 `\d{4}年\d{1,2}月\d{1,2}日` 匹配4位数字年份、1-2位数字月份和1-2位数字日期。