You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java正则表达式从字符串中提取HH:MM:SS格式时间

解决Java正则提取HH:MM:SS时间的问题

你的代码无效核心问题有两个:

  • 正则使用了非捕获组(?:...),这种组不会被分配编号,调用m.group(1)会触发IndexOutOfBoundsException——根本不存在编号为1的捕获组。
  • 变量名pattren是拼写错误(正确应为pattern),虽不影响运行,但属于语法不规范。

方案一:直接获取整个匹配结果(无需捕获组)

既然正则本身匹配的就是你要的完整时间,直接调用m.group()或m.group(0)即可(group(0)代表整个匹配内容):

System.out.println("Hello, World!");
String time = "Thu Dec 22 01:12:22 UTC 2022";
// 修正拼写错误,保留原正则逻辑
String pattern = "(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(time);

// 因仅一个匹配项,用if更高效
if (m.find()) {
    System.out.println(m.group());
}

方案二:改用捕获组提取

如果想用捕获组明确获取目标内容,把整个时间正则包裹进捕获组(...),即可通过m.group(1)获取:

System.out.println("Hello, World!");
String time = "Thu Dec 22 01:12:22 UTC 2022";
// 将整个时间格式作为捕获组1
String pattern = "((?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9])";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(time);

if (m.find()) {
    System.out.println(m.group(1));
}

内容的提问来源于stack exchange,提问作者Zoso619

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 00:20:44