Question

I would like to validate and extract the hours and minutes from a string using Regex in .NET. Just to recuperate the two numbers, separated(or not) by :. Accepted format h:m or m. Unaccepted :m, h:.

EDIT: This is to note, that the number of hours could overflow the 23 till... 32.

The overflow for hours(over 32) and minutes(over 59) I will do after values recuperation(int.Parse)


* just for fun maybe there a a relative simple regex that could filter also the >32 for hour and >59 for minute (for minutes it could be [0-5]*[0-9], for hours I don't know)?

Was it helpful?

Solution 4

Finally, the code for validating (till 32) and also obtaining values is(vb.net version):

Dim regexHour As New Regex( _ 
   "((?<hours>([012]?\d)|(3[01]))\:)?(?<minutes>[0-5]?\d)", _
    RegexOptions.ExplicitCapture)
Dim matches As MatchCollection = regexHour.Matches(value)

If matches.Count = 1 Then
  With matches(0)
    ' (!) The first group is always the expression itself. '
    If .Groups.Count = 3 Then ' hours : minutes '
      strHours = .Groups("hours").Value
      If String.IsNullOrEmpty(strHours) Then strHours = "0"
      strMinutes = .Groups("minutes").Value
    Else ' there are 1, 3 or > 3 groups '
      success = False
    End If
  End With
Else
  success = False
End If

Thanks everybody contributing to this answer!

OTHER TIPS

Are you dead set on a regex? Because DateTime.Parse would be much simpler and more powerful here.

 DateTime dt = DateTime.Parse("12:30 AM");

Then dt gives you everything you need to know about the time. DateTime.TryParse() may be better in case you are less certain it's a time string.

(?:(\d\d?):)?([0-5][0-9])

If you want to validate hours:

(?:([01]?[0-9]|2[0-3]):)?([0-5][0-9])

EDIT: Tested and corrected.


However, the best way to do this is with DateTime.ParseExact, like this: (Tested)

TimeSpan time = DateTime.ParseExact(
    input, 
    new string[] { "HH:mm", "H:mm", "mm", "%m" }, //The % is necessary to prevent it from being interpreted as a single-character standard format.
    CultureInfo.InvariantCulture, DateTimeStyles.None
).TimeOfDay;

For validation, you can use TryParseExact.

Here's the regex string. You can access the named capture groups "hours" and "minutes". Use flags "ExplicitCapture" and "Singleline".

@"^((?<hours>[0-9]{1,2}):)?(?<minutes>[0-9]{1,2})$"

You can test regexes here: http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

As mentioned, a DateTime parse call might be better unless you need to validate that only this form is allowed.

Also, negative values aren't permitted, neither are decimals. (But, the regex can be changed to include them if needed).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top