[英]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.