RegEx 用于在 JavaScript 中进行灵活的时间验证

RegEx for Flexible Time Validation in JavaScript

本文关键字:时间 验证 用于 JavaScript RegEx      更新时间:2023-09-26

我从用于时间验证的正则表达式开始,它应该检测如下字符串:

5s
3h5m
5h3m02s
05:03:02
05:03
4

我当前的正则表达式对所有这些都有效,除了一个:05:03。它将 05 检测为小时,将 03 检测为秒,但它应该是 05 作为分钟......而且我不知道如何编辑我的代码来执行此操作。

 var reTime =
 /^(?:PT)?(?:('d{1,2})[:.hH])?(?:('d{1,4})[:.mM])?(?:('d{1,6})[sS]?)?$/;

测试这个:

var hasTimeFormat = function (input) {
        var timeFormat = /([0-9]{2})':([0-9]{2})':([0-9]{2})',([0-9]{3})$/;
        if (typeof String.prototype.trim !== 'function') {
            String.prototype.trim = function () {
                return input.replace(/^'s+|'s+$/g, '');
            }
        }
        return timeFormat.test(input.trim());
    }

这很有效(例如"05:03:02,677"),如果您想添加更多内容,可以轻松添加。