正则表达式 小时:分钟 (小时 > 24)
我想使用 .NET 中的正则表达式验证和提取从字符串中提取小时和分钟。 只是为了恢复两个数字,用 :
分隔(或不分隔)。接受的格式 h:m
或 m
。不接受 :m
、h:
。
编辑: 需要注意的是,小时数可能会溢出 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 formath: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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您对正则表达式一心一意吗?因为
DateTime.Parse
在这里会更简单、更强大。然后 dt 为您提供您需要了解的有关时间的所有信息。如果您不确定它是时间字符串,
DateTime.TryParse()
可能会更好。Are you dead set on a regex? Because
DateTime.Parse
would be much simpler and more powerful here.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])
如果您想验证时间:
(?:([01]? [0-9]|2[0-3]):)?([0-5][0-9])
编辑:已测试并更正。
但是,最好的方法是使用
DateTime.ParseExact
,如下所示:(已测试)为了进行验证,您可以使用 尝试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)For validation, you can use TryParseExact.
这是正则表达式字符串。您可以访问命名的捕获组“小时”和“分钟”。使用标志“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).
最后,验证(直到 32)并获取值的代码是(vb.net 版本):
感谢大家为这个答案做出贡献!
Finally, the code for validating (till 32) and also obtaining values is(vb.net version):
Thanks everybody contributing to this answer!