【发布时间】:2016-07-05 18:39:07
【问题描述】:
我有一个包含某些记录的 csv 文件。这些记录中有各种格式的日期。我想将所有格式转换为 MM/dd/yyyy,其中任何一位数字月份或日期前面都有一个 0。问题是,当它写入文件时,它会添加一堆额外的 0,我不知道为什么。我的数据的一个例子是:
Title,Labels,Type,Current State,Created at,Accepted at,Deadline,Requested By,Description,Owned By,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment,Comment
pad,pad,epic,,9/26/2012 0:00,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
655656 add security role xxxx,user updates,chore,accepted,7/20/2012 0:00,7/23/2012 0:00,,xxxx,"Call Number: 655656
Client Name: xxxxx
Department:
Address: xxxx
Phone: (xxx)xxx-xxxx
Open Date/Time: 6/25/2012 2:50:52 PM
Opened by: MAGIC
Problem Description: Effective Date: 07/09/2012 12:00 a
Area: CASE COMPASS.
Action: ADD ACCESS
Report/other Role: NONE
App Role: FIELD()
xxxx 7/18/2012 9:17 AM: created user id and assigned roles in enterprise security
Notes:
Problem Resolution: 7/19/12 - xxxx: Access granted, AD account added to the HL_Viewer security group.
CDS\xxxx -- S-1-5-21-508124448-3695470602-466989033-155771
Magic URL: http://magicweb02/magictsd
",Jane Doe, Please verify (Jane Doe - 07/23/2012 0:00),verified (Jamie Doe -07/23/2012 00:00),,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
655977 add security role xxxx,user updates,chore,accepted,7/19/2012 0:00,7/23/2012 0:00,,xxx,"Call Number: 655977
我的代码如下所示:
try
{
string file = File.ReadAllText("C:\\\\Users\\hacknj\\Desktop\\mo_daily_activity_20160627_1412.csv");
// Define bad date
Regex badDate = new Regex(@"(\d{1,2}\/\d{1,2}\/\d{4})");
// Find Matches
MatchCollection matches = badDate.Matches(file);
// Go through each match
foreach (Match match in matches)
{
// get the match text
string matchText = match.Groups[0].ToString();
// Define DateTime
DateTime parsedDate;
DateTime.TryParse(matchText.Trim(), out parsedDate);
file = file.Replace(matchText, parsedDate.ToString("MM/dd/yyyy"));
}
File.WriteAllText("C:\\\\Users\\hacknj\\Desktop\\TestFile.csv", file);
}
以下是日期写入文件后的样子:
pad,pad,epic,,000009/26/2012 0:00,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
655656 add security role xxxx,user updates,chore,accepted,0000007/20/2012 0:00,00000007/23/2012 0:00,,xxxx,"Call Number: 655656
如果我在数据被替换之前查看数据,它看起来很好。我通过
做到这一点MessageBox.Show("Match Text: " + matchText.Trim() + "\nParsed Date: " + parsedDate.ToString("MM/dd/yyyy"));
有人能告诉我我在做什么导致在写入文件时生成这些额外的 0 吗?
【问题讨论】:
-
\d{1,2}\/\d{1,2}\/\d{4}可能会为09/26/2012返回9/26/2012。多次迭代(和替换)将导致添加额外的0。
标签: c# regex datetime writetofile tryparse