我想 证实提炼来自字符串的小时和分钟 在.NET 中使用正则表达式。只是为了恢复两个数字,分隔(或不分隔) :. 。接受的格式h:m 或者 m. 。未接受 :m, h:.

编辑:需要注意的是,这个数 小时 可能会溢出 23 直到... 32.

溢出数小时(超过 32)和分钟(超过 59)我将在值恢复(int.Parse)之后进行


* 只是为了好玩 也许有一个相对简单的正则表达式可以过滤> 32的小时和> 59的分钟(对于 分钟 它可能是 [0-5]*[0-9], ,几个小时我不知道)?

有帮助吗?

解决方案 4

最后,用于验证(直到32),并且还获得数值的代码是(vb.net版):

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

谢谢大家奉献这个答案!

其他提示

您死心塌地的正则表达式?由于DateTime.Parse就会简单得多,在这里更加强大。

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

然后DT给你你需要了解的一切时间。 DateTime.TryParse()可能的情况下,更好的是你少某些它是一个时间字符串。

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

如果您想验证时间:

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

修改:测试和校正


然而,为了做到这一点,最好的方法是用DateTime.ParseExact,像这样:(测试)

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;

有关验证,可以使用 TryParseExact

这是正则表达式字符串。您可以访问命名的捕获组“小时”和“分钟”。使用标志“ExplicitCapture”和“Singleline”。

@"^((?<小时>[0-9]{1,2}):)?(?<分钟>[0-9]{1,2})$"

您可以在这里测试正则表达式: http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

如前所述,除非您需要验证仅允许这种形式,否则 DateTime 解析调用可能会更好。

此外,不允许使用负值,也不允许使用小数。(但是,如果需要,可以更改正则表达式以包含它们)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top