C# 验证有效时间的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/884848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regular expression to validate valid time
提问by juan
Can someone help me build a regular expression to validate time?
有人可以帮我构建一个正则表达式来验证时间吗?
Valid values would be from 0:00 to 23:59.
有效值是从 0:00 到 23:59。
When the time is less than 10:00 it should also support one character numbers
时间小于10:00时也应支持一个字符数
ie: these are valid values:
即:这些是有效值:
- 9:00
- 09:00
- 9:00
- 09:00
Thanks
谢谢
采纳答案by Gumbo
Try this regular expression:
试试这个正则表达式:
^(?:[01]?[0-9]|2[0-3]):[0-5][0-9]$
Or to be more distinct:
或者更明显:
^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
回答by Nick Presta
I don't want to steal anyone's hard work but thisis exactly what you're looking for, apparently.
我不想偷任何人的辛勤工作,但是这是你在寻找什么,显然。
using System.Text.RegularExpressions;
public bool IsValidTime(string thetime)
{
Regex checktime =
new Regex(@"^(20|21|22|23|[01]d|d)(([:][0-5]d){1,2})$");
return checktime.IsMatch(thetime);
}
回答by user40552
The regex ^(2[0-3]|[01]d)([:][0-5]d)$
should match 00:00 to 23:59. Don't know C# and hence can't give you the relevant code.
正则表达式^(2[0-3]|[01]d)([:][0-5]d)$
应该匹配 00:00 到 23:59。不知道 C#,因此不能给你相关的代码。
/RS
/RS
回答by scottm
I'd just use DateTime.TryParse().
我只是使用 DateTime.TryParse()。
DateTime time;
string timeStr = "23:00"
if(DateTime.TryParse(timeStr, out time))
{
/* use time or timeStr for your bidding */
}
回答by roydukkey
If you want to allow militaryand standardwith the use of AM and PM(optional and insensitive), then you may want to give this a try.
如果您想允许军用和标准使用AM 和 PM(可选且不敏感),那么您可能想尝试一下。
^(?:(?:0?[1-9]|1[0-2]):[0-5][0-9]\s?(?:[AP][Mm]?|[ap][m]?)?|(?:00?|1[3-9]|2[0-3]):[0-5][0-9])$
回答by Percy Gutierrez
Better!!!
更好的!!!
public bool esvalida_la_hora(string thetime)
{
Regex checktime = new Regex("^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
if (!checktime.IsMatch(thetime))
return false;
if (thetime.Trim().Length < 5)
thetime = thetime = "0" + thetime;
string hh = thetime.Substring(0, 2);
string mm = thetime.Substring(3, 2);
int hh_i, mm_i;
if ((int.TryParse(hh, out hh_i)) && (int.TryParse(mm, out mm_i)))
{
if ((hh_i >= 0 && hh_i <= 23) && (mm_i >= 0 && mm_i <= 59))
{
return true;
}
}
return false;
}
回答by Ji?í Sedlák
public bool IsTimeString(string ts)
{
if (ts.Length == 5 && ts.Contains(':'))
{
int h;
int m;
return int.TryParse(ts.Substring(0, 2), out h) &&
int.TryParse(ts.Substring(3, 2), out m) &&
h >= 0 && h < 24 &&
m >= 0 && m < 60;
}
else
return false;
}
回答by user6644247
[RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9] (am|pm|AM|PM)$",
ErrorMessage = "Invalid Time.")]
Try this
尝试这个