正则表达式以validation有效时间
有人可以帮我构建一个正则表达式来validation时间吗?
有效值为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); }
我只使用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])$
正则表达式^(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; }