Javascript时间转换正则表达式 [英] Javascript time conversion regexp

查看:106
本文介绍了Javascript时间转换正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种在.Net中使用正则表达式来转换时间的方法。 1h 20m格式加倍。这是它。

I have a method using regular expressions in .Net to convert time from e.g. "1h 20m" format to double. Here is it.

public static double? GetTaskHours(this string tmpHours) {
  Double taskHours = 0;
  if (!string.IsNullOrEmpty(tmpHours) && !double.TryParse(tmpHours, out taskHours)) {
    var match = Regex.Match(tmpHours, @"^(?=\d)((?<hours>\d+)(h|:))?\s*((?<minutes>\d+)m?)?$", RegexOptions.ExplicitCapture);
    if (match.Success) {
      int hours;
      int.TryParse(match.Groups["hours"].Value, out hours);
      int minutes;
      int.TryParse(match.Groups["minutes"].Value, out minutes);
      taskHours = (double)hours + (double)minutes / 60;
    }
  }
  return Math.Round(taskHours, 3);
}

现在我需要使用相同的Javascript。我试图根据 http://www.w3schools.com/jsref/jsref_regexp_nfollow.asp转换正则表达式但我所有的努力都失败了。我的正则表达式很差。

Now I need the same using Javascript. I tried to convert the regex according to http://www.w3schools.com/jsref/jsref_regexp_nfollow.asp but all my atempts failed. I'm very poor in regular expressions.

这是我的JS尝试。

function getHours(value) {
  var myArray = value.match(/^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$/g);
  var hours = myArray[2];
  var minutes = myArray[5];
  return Number(hours) + Number(minutes) / 60;
}

这是正确的吗?

你能告诉我吗那个方式?

Is it correct?
Can you please show me the way?

问候,德米特里。

推荐答案

字符串。 match方法只返回完整匹配的数组,而不返回任何组。使用Regex.exec方法获取所有组:

The String.match method will return only an array of the complete matches, not of any groups. Use the Regex.exec method to get all the groups:

function getHours(value) {
    var myArray = (/^((\d+)(h|:))?\s*((\d+)m?)?$/g).exec(value);
    var hours = myArray[2];
    var minutes = myArray[5];
    return Number(hours) + Number(minutes) / 60;
}

这篇关于Javascript时间转换正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆