我有一个这样的字符串:
"WAIT_UNTIL;SYSTEM_TIME >= Di 15 Sep 2009 23:00:21 and IgnKeyPos ==3"
或者类似的东西
"IF;Thermal >=20 and SYSTEM_TIME >= Tue 16 Sep 2009 23:00:21 "
我只需要提取时间和日期部分,以便以后可以像这样使用它:
TimeThen = DateTime.Parse("Di 15 Sep 2009 23:00:21");
我应该如何开始?
请您参考如下方法:
这会匹配,但随着对预期格式的更多反馈,它可能会得到增强。现在它在日期/时间部分之间至少接受 1 个空格。
string input = "IF;Thermal >=20 and SYSTEM_TIME >= Tue 15 Sep 2009 23:00:21 ";
string pattern = @"[A-Z]+\s+\d+\s+[A-Z]+\s+\d{4}\s+(?:\d+:){2}\d{2}";
Match match = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
string result = match.Value;
DateTime parsedDateTime;
if (DateTime.TryParse(result, out parsedDateTime))
{
// successful parse, date is now in parsedDateTime
Console.WriteLine(parsedDateTime);
}
else
{
// parse failed, throw exception
}
}
else
{
// match not found, do something, throw exception
}
