0

我愿意接受以下格式:

"23:59", "2:3:04", "02:00:09", "23:07:00"

使用这个正则表达式模式:

return Regex.IsMatch(timeIn, @"^([0-2]?[0-9]:[0-5]?[0-9])|([0-2]?[0-9]:[0-5]?[0-9]:[0-5]?[0-9])$") ? true : false;

不幸的是,它也接受其他格式,例如:00:00:99

我究竟做错了什么?谢谢你。

4

2 回答 2

2

您缺少一组用于整个表达式的括号,位于行首和行尾锚点之间:

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

如果没有括号,您的正则表达式基本上是在说:

  • 匹配^([0-2]?[0-9]:[0-5]?[0-9])
  • 或者 ([0-2]?[0-9]:[0-5]?[0-9]:[0-5]?[0-9])$

因此,00:00:99与正则表达式的第一部分匹配是有效的。而且,类似: 的东西99:00:00:00也会与第二部分相匹配。

也就是说,您的正则表达式仍会匹配一些不需要的模式,例如:29:00

改进的版本是:

^((([0-1]?[0-9])|(2[0-3]):[0-5]?[0-9])|(([0-1]?[0-9])|(2[0-3]):[0-5]?[0-9]:[0-5]?[0-9]))$
于 2014-04-16T14:38:54.467 回答
0

Although it does not answer the question directly, I would like to say that in such a standard cases, I would rather use built-in function rather than creating real scary regular expressions:

DateTime.TryParseExact(input, "H:m:s", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
于 2014-04-16T14:43:35.207 回答