java 正则表达式提取时间字符串
时间: 2023-09-25 13:15:58 浏览: 147
可以使用正则表达式提取时间字符串,具体如下:
1. 提取小时和分钟:
```java
String timeStr = "12:30";
Pattern pattern = Pattern.compile("(\\d{1,2}):(\\d{1,2})");
Matcher matcher = pattern.matcher(timeStr);
if (matcher.find()) {
int hour = Integer.parseInt(matcher.group(1));
int minute = Integer.parseInt(matcher.group(2));
System.out.println("hour: " + hour + ", minute: " + minute);
}
```
输出:
```
hour: 12, minute: 30
```
2. 提取日期和时间:
```java
String dateTimeStr = "2021-10-01 12:30:45";
Pattern pattern = Pattern.compile("(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2})");
Matcher matcher = pattern.matcher(dateTimeStr);
if (matcher.find()) {
String dateStr = matcher.group(1);
String timeStr = matcher.group(2);
System.out.println("date: " + dateStr + ", time: " + timeStr);
}
```
输出:
```
date: 2021-10-01, time: 12:30:45
```
3. 提取时间戳:
```java
String timestampStr = "1633079445000";
Pattern pattern = Pattern.compile("(\\d{13})");
Matcher matcher = pattern.matcher(timestampStr);
if (matcher.find()) {
long timestamp = Long.parseLong(matcher.group(1));
System.out.println("timestamp: " + timestamp);
}
```
输出:
```
timestamp: 1633079445000
```
注意:以上示例仅提供了一些基本的正则表达式提取时间字符串的方法,实际应用中需要根据具体情况进行调整。
阅读全文