[英]Get all dates from a string in C#
我正在使用基於Web的DOTNET應用程序,其中我在數據庫中有一個日志列。每當用戶在UI上的注釋textarea中添加注釋時,日期,他的名字以及注釋將附加到數據庫中的現有數據。 以下是列具有數據的格式:
04/05/11 17:10:19 (user2):Work Log -
Closing.
03/31/11 09:40:02 (user2):Work Log -
Support provided over phone.
03/31/11 09:39:43 (user1):Work Log –
Awaiting support reply
03/30/11 11:30:08 (user2):Work Log -
Manager notified by standard e-mail communication.
03/30/11 11:29:30 (user1):Work Log -
Emailed support team
03/30/11 11:28:52 (user1):Work Log -
I have an issue with my Xbox.
我現在嘗試在輸入這些注釋時拉出所有日期(只是日期)。 我嘗試了很多選擇但沒有幫助。
假設您想在C#代碼中執行此操作:
Regex splitter = new Regex("[0-9]{2}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}");
foreach (Match m in splitter.Matches(theDatabaseValue)) {
string dateString = m.Groups[0].Value;
DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yy HH:mm:ss", null);
}
關於正則表達式方法的好處是你可以擴展它以提取用戶:
Regex splitter = new Regex("(?<date>[0-9]{2}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}) \\((?<user>.+)\\)");
foreach (Match m in splitter.Matches(theDatabaseValue)) {
string dateString = m.Groups["date"].Value;
DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yy HH:mm:ss", null);
string user = m.Groups["user"].Value;
Console.WriteLine("{0} {1}", dt.ToString(), user);
}
因此,即使是消息(我還沒有完成正則表達式的那部分,因為我不確定你是否在消息之前有換行符,好像你這樣做)。
完成此操作后,您可以創建一個數據庫表,其中包含三列,日期,用戶,注釋,然后使用正則表達式將現有表轉換為該表,並使您將來的生活變得更加輕松!
您應該重構數據庫以將數據存儲在三列(DateTime,User,Comment)中,這將極大地提高性能和可用性。
但是,如果這不是一個選項,您可以使用DateTime.TryParse從字符串中獲取值。 例如:
string comment = "04/05/11 17:10:19 (user2):Work Log - Closing.";
string dateSection = comment.Substring(0, 17);
DateTime date;
if (!DateTime.TryParse(dateSection, out date))
{
throw new Exception(string.Format("unable to parse string '{0}'", dateSection));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.