正则表达式 小时:分钟 (小时 > 24)

发布于 2024-08-17 03:20:33 字数 487 浏览 15 评论 0原文

我想使用 .NET 中的正则表达式验证提取从字符串中提取小时和分钟。 只是为了恢复两个数字,用 : 分隔(或不分隔)。接受的格式 h:mm。不接受 :mh:

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

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


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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

天荒地未老 2024-08-24 03:20:33

您对正则表达式一心一意吗?因为 DateTime.Parse 在这里会更简单、更强大。

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

然后 dt 为您提供您需要了解的有关时间的所有信息。如果您不确定它是时间字符串,DateTime.TryParse() 可能会更好。

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.

以可爱出名 2024-08-24 03:20:33

(?:(\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;

为了进行验证,您可以使用 尝试ParseExact

(?:(\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.

凉墨 2024-08-24 03:20:33

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

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

您可以在此处测试正则表达式: < a href="http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx" rel="nofollow noreferrer">http://derekslager.com/blog /posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

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

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

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

旧人九事 2024-08-24 03:20:33

最后,验证(直到 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

感谢大家为这个答案做出贡献!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文