如果小时,分钟和秒的顺序有效,则将t = 1h2m3s(h - 小时,m分钟,s-秒)解析为秒

时间:2015-07-22 12:51:53

标签: javascript regex

我只需要解析有效的时间戳格式,如下所示

  1. 小时后是分钟,然后是秒ex:t = 1h2m3s
  2. 分钟后秒秒:t = 2m3s
  3. 仅数小时ex:t = 3h
  4. 只有几分钟ex:t = 4m
  5. 仅秒ex:t = 5s
  6. 并转义其他时间戳格式,如t = 2m1h或t = 3s2m或t = 3s1h2m。

    我尝试了如下但无法逃避无效格式。我正在尝试使用正则表达式来查找。

     function calculateInSeconds(timeStamp) {
            var timeInSeconds=0;
            console.log("calculateInSeconds timeStamp:"+timeStamp);
    
            timeStamp.replace(/([0-9]+)[h|m|s]/g, function(match, value) {
                if (match.indexOf("h") > -1) {
                    timeInSeconds += value * 60 * 60;
                } else if (match.indexOf("m") > -1) {
                    timeInSeconds += value * 60;
                } else if (match.indexOf("s") > -1) {
                    timeInSeconds += value * 1;
                }
    
            });
            console.log("timeInSeconds"+timeInSeconds);
    
        }
    calculateInSeconds("t=20m2s");
    

3 个答案:

答案 0 :(得分:0)

使用可选的量词。

t=(?:(?:\d{1,2}h)?\d{1,2}m)?\d{1,2}s  

t=(?:(?:(?:1[012]|[1-9])h)?(?:[1-5]?\d|60)m)?(?:[1-5]?\d|60)s

答案 1 :(得分:0)

我会首先检查订单是否匹配,如果它确实以秒计算时间。



function calculateInSeconds(timeStamp) {
  var timeInSeconds=0;
  console.log("calculateInSeconds timeStamp:"+timeStamp);
  if(timeStamp.match(/t=[0-9]*h?[0-9]*m?[0-9]*s?/g).toString()==timeStamp){
    timeStamp.replace(/([0-9]+)[h|m|s]/g, function(match, value) {
       if (match.indexOf("h") > -1) {
          timeInSeconds += value * 60 * 60;
       } else if (match.indexOf("m") > -1) {
                timeInSeconds += value * 60;
       } else if (match.indexOf("s") > -1) {
                timeInSeconds += value * 1;
       }
     });
   }
   console.log("timeInSeconds"+timeInSeconds);
}
calculateInSeconds("t=1h2m");//3720 valid
calculateInSeconds("t=2m1h");//0 invalid




答案 2 :(得分:0)

检查以下正则表达式:

([0-0]?[0-4])[h]([0-5]?[0-9]|60)[m]([0-5]?[0-9]|60)[s]