我有一定格式的文本文件。 首先是一个标识符,随后三个空间和结肠。 然后是这个标识符的值。
ID1 :Value1
ID2 :Value2
ID3 :Value3
我需要做的是搜索,例如什么ID2 :
和替换Value2
用新值NewValue2
。 这将是一个办法做到这一点? 我需要解析的文件不会得到非常大的。 最大的将围绕150线。
我有一定格式的文本文件。 首先是一个标识符,随后三个空间和结肠。 然后是这个标识符的值。
ID1 :Value1
ID2 :Value2
ID3 :Value3
我需要做的是搜索,例如什么ID2 :
和替换Value2
用新值NewValue2
。 这将是一个办法做到这一点? 我需要解析的文件不会得到非常大的。 最大的将围绕150线。
如果文件不是很大,你可以做一个File.ReadAllLines
获得所有行的集合,然后替换你这样找线
using System.IO;
using System.Linq;
using System.Collections.Generic;
List<string> lines = new List<string>(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<string, string> replacements = new Dictionary<string, string>();
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);
在正则表达式,(我?)(<= ^ ID2 \ S *:???\ S *)?\ W *(= \ s * $?)表示,找到任何与ID2开始与任意数量的空格之前和之后:
,和替换下面的字符串(任何字母数字字符,标点除外)一路“直到该行的末尾。 如果您要包括标点符号,然后替换\ W *? 与*?
您可以使用正则表达式来实现这一目标。
Regex re = new Regex(@"^ID\d+ :Value(\d+)\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
List<string> 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);
}