查找字符串是否包含日期和时间
本文关键字:时间 日期 包含 字符串 是否 查找 | 更新日期: 2023-09-27 17:59:39
我正在做一个项目,我正在读取一个文件,该文件可能有两种不同的格式,一种包括日期和时间,另一种不包括。
当我读第一行时,我需要检查字符串是否包含日期和时间,然后读取文件,并根据检查以某种方式读取文件。
我猜这可能是某种正则表达式,但不知道从哪里开始,也找不到任何相关的内容。
感谢您提供的任何帮助。
更新我不太清楚我在问什么。当我逐行读取日志文件时,行可能显示为:
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 and 2nd January 2019 mnmnm ";//here is u r 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|augu|september|october|november|december)[-/./_///:/|/$/'s+][0-9]{2,4})");//a pattern for regex to check date format. For August we check Augu since we replaced the st earlier
MatchCollection mc = rx.Matches(sp);//look for strings that satisfy the above pattern regex
List<DateTime> dates=new List<DateTime>(); //Create a list to store the detected dates
foreach(Match m in mc)
{
string s2=Regex.Replace(m.ToString(), "augu", "august");
dates.Add(DateTime.Parse(s2);
}
使用此方法检查字符串是否为日期:
private bool CheckDate(String date)
{
try
{
DateTime dt = DateTime.Parse(date);
return true;
}
catch
{
return false;
}
}
这对我们有效:
如果字符串值是有效的日期时间值,那么它不会给出任何异常:
try
{
Convert.ToDateTime(string_value).ToString("MM/dd/yyyy");
}
如果字符串值是无效的日期时间值,那么它将给出异常:
catch (Exception)
{
}