开发者

Compare array format

开发者 https://www.devze.com 2023-01-11 01:20 出处:网络
I have an array which contains different blocks of data and i have to extract the blocks which contain the date and the hour. How could i do that?

I have an array which contains different blocks of data and i have to extract the blocks which contain the date and the hour. How could i do that?

string[] s={"File", "Block", "Detected:", "2010-08-11", "11:48:50", etc...} 

The date and time are not always on the same position but they do have the sa开发者_运维问答me format


Since you know that the date and the time will be at some position inside the array, you can iterate through the array and look for something that looks like a date or a time. Example:

foreach (str in s) {
    if (Regex.IsMatch(str, @"\d\d\d\d-\d\d-\d\d")) {
        // found the date
    }
}

or, using LINQ:

string myDate = (from str in s
                 where Regex.IsMatch(str, @"\d\d\d\d-\d\d-\d\d")
                 select str).First();

For identifying the time, you could use the Regex \d\d:\d\d:\d\d.

(All code untested, since I don't have Visual Studio available right now.)


        string[] sArr = { "File", "Block", "Detected:", "2010-08-11", "11:48:50", "29.01.1987 12:23" };

        foreach (var s in sArr)
        {
            DateTime d;

            if (DateTime.TryParse(s, out d))
            {
                Console.WriteLine(d);
            }
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消