如何使用正则表达式从字符串中提取所有24小时?

问题描述 投票:0回答:1

我想提取字符串中的所有24小时。

我想从中提取时间的字符串示例可能是:

The image has been uploaded at 20:12 and viewed at 21:04 and later was deleted around 23:43

我想从此示例字符串中提取3次:

  • 20:12
  • 21:04
  • 23:34

我已经尝试过这种模式:

^(([1-9]{1})|([0-1][0-9])|([1-2][0-3])):([0-5][0-9])$

但是似乎只验证时间是否正确。

javascript regex
1个回答
0
投票

您可以使用

let string = `The image has been uploaded at 20:12 and viewed at 21:04 and later was deleted around 23:43`;

let rx = /(\d+):(\d+)/g;

let match;

while ((match = rx.exec(string)) !== null) {
    if ((match[1] >= 0 && match[1] <= 24) && (match[2] >= 0 && match[2] <= 60)) {
        console.log(match[0]);
    }
}

这里您匹配任何模式digits:digits,然后验证它们是否落在JavaScript内的正确范围内。

© www.soinside.com 2019 - 2024. All rights reserved.