Bitz Bitz - 1 month ago 8
C# Question

Regex for durations (HH:MM) and splitting? (Or built in C# Splitter)?

I am trying to parse a string against the following format: HH:MM

12:23 //Normal
2:24 //No trailing 0
01:00 //With trailing 0
00:21 //00 First number
0:32 //0 First Number
10:4 //No 0 second number, denotes 10:04


First number max 24, min 0.

Second number max 59, min 0.

I made the string regex string
\d+:\d+
. But this still matches numbers outside of the ranges. What is the best way of handing these numbers?

I am doing this validation as a string in C#, if there is a better way of validating this format (and splitting it into hours and minutes, please let me know!)

Basically I am accepting the input as HH:MM, validating it, splitting it and then converting it into an
int
of minutes.

Example:


  1. User enters 10:20

  2. Checks format validation
    HH:MM

  3. Checks range validation
    (0-24):(0-60)

  4. Splits into variables
    int hrs = 10
    and
    int mins = 20

  5. return (mins + (hrs*60));


Answer

You can use TimeSpan.TryParse. This has the added benefit of calculating the minutes for you via the TotalMinutes property:

List<string> tests = new List<string>()
{
    "12:23", //Normal
    "2:24", //No trailing 0
    "01:00", //With trailing 0
    "00:21", //00 First number
    "0:32", //0 First Number
    "10:4", //No trailing 0 second number
};

foreach (var test in tests)
{
    TimeSpan t;
    if (TimeSpan.TryParse(test, out t))
        Console.WriteLine(t.TotalMinutes);
    else
        Console.WriteLine("Not valid");
}

Which outputs:

743
144
60
21
32
604

@AlexK correctly points out in the comments that this will match strings that include seconds such as 11:22:33. To prevent that you can use TryParseExact and pass an array of acceptable formats:

List<string> tests = new List<string>()
{
    "12:23", //Normal
    "2:24", //No trailing 0
    "01:00", //With trailing 0
    "00:21", //00 First number
    "0:32", //0 First Number
    "10:4", //No trailing 0 second number
    "11:22:33", //Error
};

foreach (var test in tests)
{
    TimeSpan t;
    //if (TimeSpan.TryParse(test, out t))
    if (TimeSpan.TryParseExact(test, new[] { "h\\:m", "hh\\:m", "hh\\:m", "h\\:mm", "hh\\:mm" }, CultureInfo.CurrentCulture, out t))
        Console.WriteLine(t.TotalMinutes);
    else
        Console.WriteLine("Failed");
}

Which outputs

743
144
60
21
32
604
Failed

Comments