我需要一个正则表达式来验证时间格式。有效的时间范围是从0:00到23:59。当时间小于10:00时,正则表达式应该支持单个数字。以下是有效的时间格式:
- 9:00
- 09:00
尝试使用这个正则表达式:
^(?:[01]?[0-9]|2[0-3]):[0-5][0-9]$
更明确地说:
^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
我不想抄袭任何人的辛勤工作,但这篇文章似乎正是你要找的。
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);
}
d
字符只能匹配字面上的字符 d
,所以对于 "00:00"
和 "23:59"
它返回 false
,但对于 "0d:0d"
却返回 true
。它们应该改为 \d
或 [0-9]
来匹配任何十进制数字。该博客文章的下一行,这里没有提到,是 "时间正则表达式 用于控制时间的是 ^(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})$
"。 - Lance U. Matthews我会使用 DateTime.TryParse()。
DateTime time;
string timeStr = "23:00"
if(DateTime.TryParse(timeStr, out time))
{
/* use time or timeStr for your bidding */
}
如果您想允许使用上午和下午(可选且不区分大小写)来表示时间的军事时间制和标准时间制,那么您可以尝试以下方法。
^(?:(?: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])$
^(2[0-3]|[01]\d)([:][0-5]\d)$
应匹配00:00到23:59。我不懂C#,因此无法提供相关代码。虽然有点晚了,但我创建了这个正则表达式,我发现它对于24小时制的时间格式(HH:mm:ss或HH:mm或H:mm:ss或H:mm)效果最佳:
private bool TimePatternValidation(string time)
=> new Regex(@"^(([0-1]?[0-9])|([2][0-3]))(:([0-5][0-9])){1,2}$").IsMatch(time);
[RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9] (am|pm|AM|PM)$",
ErrorMessage = "Invalid Time.")]
试试这个
更好!!!
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;
}
00:00
,01:00
,……是有效值吗? - Gumbo