C# 用于验证有效时间的正则表达式
有人能帮我建立一个正则表达式来验证时间吗 有效值的范围为0:00到23:59 当时间小于10:00时,它还应支持一个字符的数字 ie:这些是有效值:C# 用于验证有效时间的正则表达式,c#,.net,regex,C#,.net,Regex,有人能帮我建立一个正则表达式来验证时间吗 有效值的范围为0:00到23:59 当时间小于10:00时,它还应支持一个字符的数字 ie:这些是有效值: 九点 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; pub
- 九点
- 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);
}
正则表达式^(2[0-3]|[01]d)([:][0-5]d)$
应匹配00:00到23:59。不知道C#,因此无法提供相关代码
/RS我只需要使用DateTime.TryParse()
如果您想允许使用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])$
更好
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 esvalida_la_hora(字符串时间)
{
Regex checktime=newregex(“^(?:0?[0-9]| 1[0-9]| 2[0-3]):[0-5][0-9]$”;
如果(!checktime.IsMatch(时间))
返回false;
如果(time.Trim()长度<5)
时间=时间=“0”+时间;
字符串hh=time.Substring(0,2);
字符串mm=时间。子字符串(3,2);
int hh_i,mm_i;
如果((内锥巴色(hh,out hh_i))&&(内锥巴色(mm,out mm_i)))
{
如果((hh_i>=0&&hh_i=0&&mm_ipublic bool IsTimeString(字符串ts)
{
如果(ts.Length==5&&ts.Contains(':'))
{
int-h;
int m;
返回int.TryParse(ts.Substring(0,2),out h)&&
内锥巴色(ts.子串(3,2),外m)&&
h>=0&&h<24&&
m>=0&&m<60;
}
其他的
返回false;
}
试试这个对不起,我输入错了,我希望第一个数字支持1个字符。例如:2:00和02:00是00:00
,01:00
,…有效值?你只需要正则表达式答案有什么原因吗?它用于正则表达式验证它用于客户端验证在你的答案中添加更多详细信息。为什么OP“试试这个”?一个好的答案总是会有一个解释,说明做了什么以及为什么这样做,不仅是为了OP,而且是为了未来的访客,这样他们可能会发现这个问题并阅读你的答案。为什么这样更好?这个答案似乎不符合问题的标准?
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;
}
[RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9] (am|pm|AM|PM)$",
ErrorMessage = "Invalid Time.")]