查找字符串是否包含日期和时间

Boa*_*rdy 9 c#

我正在开展一个项目,我正在阅读一个文件,该文件可能有两种不同的格式,一种包括日期和时间,另一种则没有.

当我在第一行读到时,我需要检查字符串是否包含日期和时间,并读取文件并根据检查以某种方式读取文件.

我猜这将是某种正则表达,但不知道从哪里开始,找不到任何相关的东西.

感谢您的任何帮助,您可以提供.

更新 我不认为我一直非常清楚我在问什么.当我逐行读取日志文件时,该行可能会出现如下:

Col1   Col2  Col3  Col4  Col5 
Run Code Online (Sandbox Code Playgroud)

有时这条线可能会出现

Col1  17-02-2013 02:05:00 Col2  Col3  Col4  Col5
Run Code Online (Sandbox Code Playgroud)

当我读取该行时,我需要检查字符串中是否包含日期和时间字符串.

小智 17

如果已定义日期格式,则可以使用Regex解决该问题.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace RegTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string testDate = "3214312402-17-2013143214214";
            Regex rgx = new Regex(@"\d{2}-\d{2}-\d{4}");
            Match mat = rgx.Match(testDate);
            Console.WriteLine(mat.ToString());
            Console.ReadLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


amh*_*hed 5

更新2:使用DateTime.TryParseExact发现是使用Regex表达式的更好方法

DateTime myDate;
if (DateTime.TryParseExact(inputString, "dd-MM-yyyy hh:mm:ss", 
    CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate))
{
    //String has Date and Time
}
else
{
    //String has only Date Portion    
}
Run Code Online (Sandbox Code Playgroud)

  • @amhed:如果`DateTime.TryParse(x)`返回一个布尔值,如果成功或不成功,则无需检查minvalue.也就是说,如果它没有成功,它将始终返回false. (3认同)