使用C#搜索和替换文本文件中的值
我有一个具有特定格式的文本文件。 首先是一个标识符,后跟三个空格和一个冒号。 然后是此标识符的值。
ID1 :Value1 ID2 :Value2 ID3 :Value3
我需要做的是搜索例如ID2 :
并用新值NewValue2
替换Value2
。 怎么办呢? 我需要解析的文件不会变得非常大。 最大的将是约150行。
如果文件不是那么大,你可以做一个File.ReadAllLines
来获取所有行的集合,然后替换你正在寻找的行,就像这样
using System.IO; using System.Linq; using System.Collections.Generic; List lines = new List (File.ReadAllLines("file")); int lineIndex = lines.FindIndex(line => line.StartsWith("ID2 :")); if (lineIndex != -1) { lines[lineIndex] = "ID2 :NewValue2"; File.WriteAllLines("file", lines); }
这是一个简单的解决方案,它还可以自动创建源文件的备份。
替换存储在Dictionary
对象中。 它们键在行的ID上,例如“ID2”,值是需要的字符串替换。 只需使用Add()
根据需要添加更多。
StreamWriter writer = null; Dictionary replacements = new Dictionary(); replacements.Add("ID2", "NewValue2"); // ... further replacement entries ... using (writer = File.CreateText("output.txt")) { foreach (string line in File.ReadLines("input.txt")) { bool replacementMade = false; foreach (var replacement in replacements) { if (line.StartsWith(replacement.Key)) { writer.WriteLine(string.Format("{0} :{1}", replacement.Key, replacement.Value)); replacementMade = true; break; } } if (!replacementMade) { writer.WriteLine(line); } } } File.Replace("output.txt", "input.txt", "input.bak");
您只需将input.txt
, output.txt
和input.bak
替换为源,目标和备份文件的路径。
通常情况下,对于任何文本搜索和替换,我建议使用某种正则表达式,但如果这就是你所做的一切,那真是太过分了。
我只想打开原始文件和临时文件; 一次读取原始行,只需检查每行“ID2:”; 如果找到它,请将替换字符串写入临时文件,否则,只需写下您读取的内容即可。 当您的源代码用完时,关闭它们,删除原始文件,并将临时文件重命名为原始文件。
这样的事情应该有效。 它非常简单,不是最有效的东西,但对于小文件,它会很好:
private void setValue(string filePath, string key, string value) { string[] lines= File.ReadAllLines(filePath); for(int x = 0; x < lines.Length; x++) { string[] fields = lines[x].Split(':'); if (fields[0].TrimEnd() == key) { lines[x] = fields[0] + ':' + value; File.WriteAllLines(lines); break; } } }
您可以使用正则表达式并在3行代码中执行此操作
string text = File.ReadAllText("sourcefile.txt"); text = Regex.Replace(text, @"(?i)(?<=^id2\s*?:\s*?)\w*?(?=\s*?$)", "NewValue2", RegexOptions.Multiline); File.WriteAllText("outputfile.txt", text);
在正则表达式中, (?i)(?<= ^ id2 \ s *?:\ s *?)\ w *?(?= \ s *?$)意味着,找到任何以id2开头的任意数量的空格之前和之后:
,并将“直到行尾”的所有方式替换为以下字符串(任何字母数字字符,不包括标点符号)。 如果要包含标点符号,请替换\ w *? 用。*?
您可以使用正则表达式来实现此目的。
Regex re = new Regex(@"^ID\d+ :Value(\d+)\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); List lines = File.ReadAllLines("mytextfile"); foreach (string line in lines) { string replaced = re.Replace(target, processMatch); //Now do what you going to do with the value } string processMatch(Match m) { var number = m.Groups[1]; return String.Format("ID{0} :NewValue{0}", number); }