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

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

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

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

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

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

Col1 Col2 Col3 Col4 Col5 

有时这条线可能会进来

 Col1 17-02-2013 02:05:00 Col2 Col3 Col4 Col5 

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

如果已定义日期格式,则可以使用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(); } } } 

更新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 } 
  string s = "Subject: Current account balances for 21st December 2017 mnmnm ";//here is ur sample string s = s.ToLower(); string newStrstr = Regex.Replace(s, " {2,}", " ");//remove more than whitespace string newst = Regex.Replace(newStrstr, @"([\s+][-/./_///://|/$/\s+]|[-/./_///://|/$/\s+][\s+])", "/");// remove unwanted whitespace eg 21 -dec- 2017 to 21-07-2017 newStrstr = newst.Trim(); Regex rx = new Regex(@"(st|nd|th|rd)");//21st-01-2017 to 21-01-2017 string sp = rx.Replace(newStrstr, ""); rx = new Regex(@"(([0-2][0-9]|[3][0-1]|[0-9])[-/./_///://|/$/\s+]([0][0-9]|[0-9]|[1][0-2]|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|january|february|march|april|may|june|july|august|september|october|november|december)[-/./_///:/|/$/\s+][0-9]{2,4})");//a pattern for regex to check date format Match m = rx.Match(sp);//look for string satisfy the above pattern regex s = m.ToString();//convert matching data to string DateTime st = Convert.ToDateTime(s);//converting that data 

使用此方法检查字符串是否为日期:

 private bool CheckDate(String date) { try { DateTime dt = DateTime.Parse(date); return true; } catch { return false; } } 

这对我们有用:

如果字符串值是有效的日期时间值,则它不会给出任何exception:

 try { Convert.ToDateTime(string_value).ToString("MM/dd/yyyy"); } 

如果字符串值是无效的日期时间值,那么它将给出exception:

 catch (Exception) { }