有没有更好的方法来编写以下方法

本文关键字:方法 更好 有没有 | 更新日期: 2023-09-27 17:57:15

以下

方法有更好、更优雅的解决方案吗?

预期输入格式:

8 h 13 m

预期输出格式:

8.13

我的代码:

private string FormatHours(string value)
{
    //Example: (Input = 10 h 53 m) (Output = 10.53) 
    var timeValues = Regex.Split(value, @"['shm]", RegexOptions.IgnoreCase).Where(s => !string.IsNullOrEmpty(s)).ToArray();
    return ((timeValues != null) && (timeValues.Length == 2)) ? string.Format(@"{0:hh}.{1:mm}", timeValues[0], timeValues[1]) : null;
}

有没有更好的方法来编写以下方法

有理由不使用以下吗?

value.Replace(" h ",".").Replace(" m",string.Empty)

我认为Regex.Split在这里矫枉过正。普通的旧Match会给你你想要的:

private static string FormatHours(string value)
{
    Match m = Regex.Match(value, @"^(?<hours>'d{1,2}) h (?<minutes>'d{1,2}) m$");
    if (m.Success)
    {
        int hours = int.Parse(m.Groups["hours"].Value);
        int minutes = int.Parse(m.Groups["minutes"].Value);
        if (hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60)
            return string.Concat(hours, ".", minutes);
    }
    return null;   
}

我唯一能想到的是,如果timeValues null打电话ToArray()会扔

    private string FormatHours(string value)
    {
        var timeValues = Regex.Split(value, @"['shm]", RegexOptions.IgnoreCase).Where(s => !string.IsNullOrEmpty(s));
        if (timeValues == null || timeValues.Count() != 2)
            return null;
        string[] arr = timeValues.ToArray();
        return string.Format(@"{0:hh}.{1:mm}", arr[0], arr[1]);
    }

表达式:

^('d{1,2}) h ('d{1,2}) m$

法典:

var input = "8 h 13 m";
var regex = new Regex(@"^('d{1,2}) h ('d{1,2}) m$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
var match = regex.Match(input);
if (!match.Success) throw new Exception();
int h = Int32.Parse(match.Groups[1].Value);
int m = Int32.Parse(match.Groups[2].Value);
var output = String.Format("{0}.{1}", h, m);
// or to be sure that that's the realistic numbers
var today = DateTime.Now;
var output2 = new DateTime(today.Year, today.Month, today.Day, h, m, 0).ToString("hh.mm");

LINQ 并不适合您的问题。以与您正在做的事情略有不同的方式使用正则表达式是我会做的:

String FormatHours(String value) {
  var regex = new Regex(@"^(?<hours>'d{1,2})'s*h's*(?<minutes>'d{1,2})'s*m$");
  var match = regex.Match(value);
  if (match.Success) {
    var hours = Int32.Parse(match.Groups["hours"].Value);
    var minutes = Int32.Parse(match.Groups["minutes"].Value);
    if (hours < 24 && minutes < 60)
      return hours + "." + minutes;
  }
  return null;
}

您可以调整正则表达式以满足您的确切需求。这个接受像 10 h 53 m10h53m 这样的字符串。