[英]Regular expression to validate valid time
有人可以幫我構建一個正則表達式來驗證時間嗎?
有效值是從 0:00 到 23:59。
時間小於10: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);
}
我只是使用 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])$
聚會很晚,但我創建了這個 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);
正則表達式^(2[0-3]|[01]d)([:][0-5]d)$
應該匹配 00:00 到 23:59。 不知道 C#,因此不能給你相關的代碼。
/RS
[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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.