[英]Replace the content between specific two text lines in a text file using regular expression
我需要在特定的两行之间替换文本文件中的内容。 所以我打算为此使用reguler表达式。
这是我的.txt
文件
text text text text text text
text text text text text text
text text text text text text
//DYNAMIC-CONTENT-START
text text text text text text
text text text text text text
//DYNAMIC-CONTENT-END
text text text text text text
text text text text text text
我需要在//DYNAMIC-CONTENT-START
和//DYNAMIC-CONTENT-END
之间替换内容。 这是正则表达式将使用的C#代码。
File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement"));
所以我的问题是我在这里可以使用什么正则表达式( [pattern]
)?
尝试:
(?is)(?<=//DYNAMIC-CONTENT-START).*?(?=//DYNAMIC-CONTENT-END)
对于您的情况,我建议您采用其他方式(逐行分析以提高性能)。 如我所见,您仅使用替换的文本将文件从输入重写为输出,因此我认为将整个过程读入内存是没有意义的。 如果您不想使用这种方法,请参见Tim Tang的答案。
using (var reader = new StreamReader(@"C:\t\input.txt"))
using (var writer = new StreamWriter(@"C:\t\Output.txt"))
{
string line;
var insideDynamicContent = false;
while ((line = reader.ReadLine()) != null)
{
if (!insideDynamicContent
&& !line.StartsWith(@"//DYNAMIC-CONTENT-START"))
{
writer.WriteLine(line);
continue;
}
if (!insideDynamicContent)
{
writer.WriteLine("[replacement]");
// write to file replacemenet
insideDynamicContent = true;
}
else
{
if (line.StartsWith(@"//DYNAMIC-CONTENT-END"))
{
insideDynamicContent = false;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.