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

jua*_*uan 15 .net c# regex

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

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

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

即:这些是有效值:

  • 9:00
  • 09:00

谢谢

Gum*_*mbo 41

试试这个正则表达式:

^(?:[01]?[0-9]|2[0-3]):[0-5][0-9]$
Run Code Online (Sandbox Code Playgroud)

或者更加明显:

^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
Run Code Online (Sandbox Code Playgroud)


Nic*_*sta 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);
}
Run Code Online (Sandbox Code Playgroud)


sco*_*ttm 7

我只使用DateTime.TryParse().

DateTime time;
string timeStr = "23:00"

if(DateTime.TryParse(timeStr, out time))
{
  /* use time or timeStr for your bidding */
}
Run Code Online (Sandbox Code Playgroud)