将计时器与 h:m:s 匹配的正则表达式

Regex to match a timer with h:m:s

我一直在努力匹配来自客户端的变量。它是这样写的:

0s
12s
1m15s
15m0s
1h0m5s
1h15m17s

我想在一次查找中捕获所有三组数字。

(\d+)(?=h(\d+)m(\d+))*?(?=m(\d+))*?

我在上面一直在研究的正则表达式只会在每个新发现中获取连续的组。

示例:

input is 12s group 1 is 12 ... works.

输入是 1m12s 第 1 组是 1 但是要得到 12,我必须再次使用 find 才能找到下一组 12。

请注意,因为我没有立即想到,请确保检查一个组是否为空以捕获可选的组。

试试这个方法:

((\d+)h)?((\d+)m)?((\d+)s)

然后您捕获第 2 组的小时数、第 4 组的分钟数和第 6 组的秒数

看到它在这里工作:https://regex101.com/r/bZ4zW4/2

以图形方式:

Debuggex Demo

编辑

要获得 JAVA 中的结果(自您上次编辑以来),请执行以下操作:

Pattern p = Pattern.compile("((\d+)h)?((\d+)m)?((\d+)s)");
Matcher m = p.matcher("1h15m17s");
if (m.find()){
    Integer hour = Integer.valueOf(m.group(2));
    Integer minute = Integer.valueOf(m.group(4));
    Integer second = Integer.valueOf(m.group(6));
    System.out.println(hour + " - " + minute + " - " + second);
}

m = p.matcher("1h0m5s");
if (m.find()){
    Integer hour = Integer.valueOf(m.group(2));
    Integer minute = Integer.valueOf(m.group(4));
    Integer second = Integer.valueOf(m.group(6));
    System.out.println(hour + " - " + minute + " - " + second);
}

m = p.matcher("15m0s");
if (m.find()){
    Integer minute = Integer.valueOf(m.group(4));
    Integer second = Integer.valueOf(m.group(6));
    System.out.println(minute + " - " + second);
}

m = p.matcher("12s");
if (m.find()){
    Integer second = Integer.valueOf(m.group(6));
    System.out.println(second);
}

m = p.matcher("0s");
if (m.find()){
    Integer second = Integer.valueOf(m.group(6));
    System.out.println(second);
}

输出将分别为:

1 - 15 - 17
1 - 0 - 5
15 - 0
12
0

请注意,在每种情况下我都会得到一个特定的值。如果您尝试从不存在的 matcher 中获取一分钟,您将得到一个 java.lang.NumberFormatException,因为它将 return 为空。所以你必须先检查一下。下面的块将在提到的异常中结束:

m = p.matcher("0s");
if (m.find()){
    Integer minute = Integer.valueOf(m.group(4)); //exception here
    Integer second = Integer.valueOf(m.group(6));
    System.out.println(second);
}