0

I am using a web based DOTNET application in which I have a log column in database, Whenever user adds a comments in comments textarea on UI, the date, his name along with the comment are appended to the exisiting data in database. Below is the format in which the column has data:

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.

I am trying to now pull all the dates (just the dates) when these comments are entered. I tried many options but none helped.

4

2 回答 2

2

假设您想在 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);
}

因此甚至是消息(我还没有完成正则表达式的那部分,因为我不确定你在消息之前是否有换行符,看起来你有)。

完成此操作后,您可以创建一个包含三列(日期、用户、评论)的数据库表,然后使用正则表达式将现有表转换为该表,让您未来的生活更轻松!

于 2013-06-13T09:50:45.893 回答
0

您应该重构数据库以将数据存储在三列(日期时间、用户、评论)中,这将大大提高性能和可用性。

但如果这不是一个选项,您可以使用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));
        }
于 2013-06-13T09:53:13.183 回答