大家好,请教一下Java如何判断字符串是否以:hh:mm:ss 时间格式开头?
可以使用正则表达式来判断一个字符串是否以hh:mm:ss时间格式开头。
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
String str = "12:34:56 Hello World";
String pattern = "^\\d{2}:\\d{2}:\\d{2}";
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher(str);
if (matcher.find()) {
System.out.println("字符串以hh:mm:ss时间格式开头");
} else {
System.out.println("字符串不以hh:mm:ss时间格式开头");
}
}
}
在上面的示例中,我们使用正则表达式 ^\d{2}:\d{2}:\d{2} 来匹配以两位数字冒号两位数字冒号两位数字开头的字符串。如果匹配成功,则说明字符串以hh:mm:ss时间格式开头。
用正则表达式
^ 表示字符串的开头
([01]?\\d|2[0-3]) 表示小时,0到23之间
: 表示冒号
([0-5]?\\d) 表示分钟,0到59之间的一个或两位数字
([0-5]?\\d) 表示秒钟,0到59之间的一个或两位数字
// 创建一个Pattern对象,编译正则表达式
Pattern pattern = Pattern.compile("^([01]?\\d|2[0-3]):([0-5]?\\d):([0-5]?\\d)");
// 创建一个Matcher对象,对字符串进行匹配
Matcher matcher = pattern.matcher("12:34:56");
// 调用matches方法,判断是否匹配
boolean result = matcher.matches();
// 打印结果
System.out.println(result);
/**
* @author qisw
* @date 2019-12-05 11:06
* @return
* @throws
* @desc 根据时间戳 转成 时间格式字符串(yyyy-MM-dd HH:mm:ss)
*/
public static String getTimestrByTimeStamp(String seconds){
if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
return "";
}
Date date=new Date(Long.valueOf(seconds+"000"));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd : HH:mm:ss");
return format.format(date);
}