Search code examples
.netregextimehour

regex hour:minute (hour > 24)


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)?


Solution

  • 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!