我正在尝试在给定位置的文件中计算一些字符串,然后将这些值放在某些节点中。 我试过以下代码
var workingPath=@"D:\Test\MyFiles";
var files = new List<string>();
if (Directory.Exists(workingPath))
{
foreach (var f in Directory.GetDirectories(workingPath, "xml",
SearchOption.AllDirectories))
{
files.AddRange(Directory.GetFiles(f, "*.xml"));
}
}
foreach (var file in files) {
string text = File.ReadAllText(file);
int fig_count = Regex.Matches(text, @"fig id=""fig").Count;
int tab_count = Regex.Matches(text, @"table-wrap id=""table").Count;
int eq_count = Regex.Matches(text, @"disp-formula id=""deqn").Count;
File.WriteAllText(file,Regex.Replace(File.ReadAllText(file), @"<fig-count count=""\d+""/>",@"<fig-count count="""+fig_count+@"""/>"));
File.WriteAllText(file,Regex.Replace(File.ReadAllText(file), @"<table-count count=""\d+""/>",@"<table-count count="""+tab_count+@"""/>"));
File.WriteAllText(file,Regex.Replace(File.ReadAllText(file), @"<eq-count count=""\d+""/>",@"<eq-count count="""+eq_count+@"""/>"));
}
代码有效,但有点多余。谁能告诉我如何减少冗余?
答案 0 :(得分:3)
我建议提取TextUpdate方法并阅读&amp;只写一次文件:
foreach (var file in files)
{
string text = File.ReadAllText(file);
text = UpdateText(text, "fig", Regex.Matches(text, @"fig id=""fig").Count);
text = UpdateText(text, "table", Regex.Matches(text, @"table-wrap id=""table").Count);
text = UpdateText(text, "eq", Regex.Matches(text, @"disp-formula id=""deqn").Count);
File.WriteAllText(file, text);
}
private static string UpdateText(string text, string type, int count)
{
return Regex.Replace(text, "<" + type + @"-count count=""\d+""/>", "<" + type + @"-count count=""" + count + @"""/>");
}
答案 1 :(得分:2)
以下代码只读取和写入文件一次:
string text = File.ReadAllText(file);
int fig_count = Regex.Matches(text, @"fig id=""fig").Count;
int tab_count = Regex.Matches(text, @"table-wrap id=""table").Count;
int eq_count = Regex.Matches(text, @"disp-formula id=""deqn").Count;
text = Regex.Replace(text, @"<fig-count count=""\d+""/>", @"<fig-count count=""" + fig_count + @"""/>");
text = Regex.Replace(text, @"<table-count count=""\d+""/>", @"<table-count count=""" + tab_count + @"""/>");
text = Regex.Replace(text, @"<eq-count count=""\d+""/>", @"<eq-count count=""" + eq_count + @"""/>");
File.WriteAllText(file, text);