我有一个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.
CDSxxxx -- 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被写入文件时生成?
额外的零是这一行在循环中运行的结果:
file = file.Replace(matchText, parsedDate.ToString("MM/dd/yyyy"));
如果相同的日期在文件中出现了不止一次,每次你的正则表达式找到一个,上面的行替换所有的。因此,如果日期需要一个前导零,则每次运行这行时,所有匹配的日期都得到一个新的前导零。
相反,您可以使用Regex.Replace()
和MatchEvaluator
函数来重新格式化匹配的日期:
var newFile = Regex.Replace(file, @"(d{1,2}/d{1,2}/d{4})", m =>
{
string matchText = m.Groups[0].ToString();
DateTime parsedDate;
if (DateTime.TryParse(matchText.Trim(), out parsedDate))
{
return parsedDate.ToString("MM/dd/yyyy");
}
else
{
return matchText;
}
});
File.WriteAllText("C:\\Users\hacknj\Desktop\TestFile.csv", newFile);
变化
-
Regex badDate = new Regex(@"(d{1,2}/d{1,2}/d{4})");
到 -
Regex badDate = new Regex(@"d{1,2}/d{1,2}/d{4}");
(去掉括号)。
-
string matchText = match.Groups[0].ToString();
到 -
string matchText = match.Groups[0].Captures.ToString();
同样,如果您想捕获日、月和年。它能在紧要关头完成工作。不需要在循环中进行替换(字符串是不可变的,所以这是一个坏主意)。你不用担心int。当你被函数体覆盖时,解析抛出异常只会在内容匹配你定义的模式(2位数,2位数,2位数或4位数)时执行
Regex badDate = new Regex(@"(?<Month>d{1,2})/(?<Day>d{1,2})/(?<Year>(20)?d{2})");
File.WriteAllText(
path,
badDate.Replace(
file,
m => {
var year = int.Parse(m.Groups["Year"].Value);
var month = int.Parse(m.Groups["Month"].Value);
var day = int.Parse(m.Groups["Day"].Value);
if (year < 2000) year += 2000;
var datetime = new DateTime(year, month, day);
return datetime.ToString("MM/dd/yyyy");
}
)
);
(?<NamedGroup>RegexPattern)
语法使事情更容易调试&消费代码更容易阅读。它仍然是正则表达式,但总比没有强。我改变了你的年份模式,可以选择接受20后面正好跟着2位数字。这应涵盖2000年至2099年期间的2位数或4位数年份。根据需要进行调整。我为即将出现的y2100 bug向你的祖先道歉。