【发布时间】:2011-03-18 14:56:52
【问题描述】:
我需要知道给定字符串是否是有效的 DateTime 格式字符串,因为该字符串可能代表其他内容。我试过 DateTime.ParseExact(somedate.ToString(format), format) 认为它会在无效格式上出错,但事实并非如此。
所以我很擅长简单地测试字符串是否只包含“yYmMdDsShH”字符。像 std::string.find_first_not_of 这样的东西可以工作,但 System.String 没有这个。
我认为 RegEx 可以解决问题,但我在正则表达式方面非常薄弱。
请注意,Linq 不适用于此版本(仅限 .NET 2.0)。
更新
为了澄清,我需要知道给定的字符串是否代表日期时间格式,而不是其他类似的东西:
if (input == "some special value")
... // it's a special case value
else if (Environment.GetEnvironmentVariable(input))
... // it's an environment variable name
else if (IsDateTimeFormatString(input))
... // it's a date time format string
else if (input.IndexOfAny(Path.GetInvalidPathChars()) < 0)
... // it's a file path
else
throw new Exception(); // Not a valid input
我可以将 DateTime 格式字符串限制为仅“yYmMdDsShH”,或者我也可以在其中添加一些分隔符,这取决于我允许或不允许什么。
【问题讨论】:
-
您是在寻找字符串字符(yYmM.. 等)还是那里的数值? (100720(今天)?