正则表达式以验证有效时间

时间:2009-05-19 20:26:24

标签: c# .net regex

有人可以帮我构建一个正则表达式来验证时间吗?

有效值为0:00至23:59。

当时间小于10:00时,它也应该支持一个字符数

即:这些是有效值:

  • 9:00
  • 09:00

由于

9 个答案:

答案 0 :(得分:39)

试试这个正则表达式:

^(?:[01]?[0-9]|2[0-3]):[0-5][0-9]$

或者更明确:

^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$

答案 1 :(得分:8)

我不想偷任何人的辛勤工作,但this正是你所寻找的,显然。

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 :(得分:7)

我只使用DateTime.TryParse()。

DateTime time;
string timeStr = "23:00"

if(DateTime.TryParse(timeStr, out time))
{
  /* use time or timeStr for your bidding */
}

答案 3 :(得分:3)

如果您想使用军事标准并允许 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])$ 

答案 4 :(得分:3)

聚会很晚,但我创建了这个 Regex 表达式,我发现它最适合 24H 格式(HH:mm:ss OR HH:mm):

private bool TimePatternValidation(string time)
    => new Regex(@"^(([0-1][0-9])|([2][0-3]))(:([0-5][0-9])){1,2}$").IsMatch(time);

答案 5 :(得分:1)

正则表达式^(2[0-3]|[01]d)([:][0-5]d)$应匹配00:00到23:59。不知道C#因此无法提供相关代码。

/ RS

答案 6 :(得分:0)

[RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9] (am|pm|AM|PM)$", 
                   ErrorMessage = "Invalid Time.")]

试试这个

答案 7 :(得分:-1)

更好!!!

    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;
    }

答案 8 :(得分:-1)

    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;
    }
相关问题