繁体   English   中英

如何从变量String解析DateTime SubString

[英]How to parse DateTime SubString out of variable String

我有一个像这样的字符串:

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

考虑使用正则表达式

以下是在C#中使用它们的一些信息:

这是一个示例用法

Regex dateTimeRegex = new Regex("\w<=(?<ParsedDateTime>YOUR REGEX GOES HERE)");

if(match.Success && match.Groups["ParsedDateTime"].Success)
{
   string parsedDateTime = match.Groups["ParsedDateTime"].Value;

   // process your parsed value here
}
(?<trash>.*?)<?<arrow>\s\>\=\s)(?<dow>\w{2,3})\s*(?<day>\d{1,2})\s*(?<month>\w{3})\s*(?<time>\d{1,2}\:\d{1,2}\:\d{1,2}).*

像第一个这样的正则表达式?

private static DateTime ExtractDateTime(string format)
{
    int length = format.Length;
    for (int startIndex = 0; startIndex < length; startIndex++)
    {
        for(int subLength = length - startIndex; subLength > 0; subLength--)
        {
            string substring = format.Substring(startIndex, subLength);
            DateTime result;
            if (DateTime.TryParse(substring, out result))
            {
                return result;
            }
        }
    }
    return DateTime.MinValue;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM