[英]Regular expression to validate valid time
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:即:这些是有效值:
Thanks谢谢
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]$
I don't want to steal anyone's hard work but this is 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);
}
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 */
}
如果您想允许使用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])$
Very late to the party but I created this Regex expression which i found work the best for 24H format (HH:mm:ss):聚会很晚,但我创建了这个 Regex 表达式,我发现它最适合 24H 格式 (HH:mm:ss):
private bool TimePatternValidation(string time)
=> new Regex(@"^(([0-1][0-9])|([2][0-3]))(:([0-5][0-9])){1,2}$").IsMatch(time);
The regex ^(2[0-3]|[01]d)([:][0-5]d)$
should match 00:00 to 23:59.正则表达式
^(2[0-3]|[01]d)([:][0-5]d)$
应该匹配 00:00 到 23:59。 Don't know C# and hence can't give you the relevant code.不知道 C#,因此不能给你相关的代码。
/RS /RS
[RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9] (am|pm|AM|PM)$",
ErrorMessage = "Invalid Time.")]
Try this试试这个
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;
}
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.