C# 使用正则表达式替换文本文件中特定两行文本之间的内容

C# 使用正则表达式替换文本文件中特定两行文本之间的内容,c#,regex,C#,Regex,我需要在特定的两行之间替换文本文件中的内容。所以我打算用正则表达式来表示这个 这是我的.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 te

我需要在特定的两行之间替换文本文件中的内容。所以我打算用正则表达式来表示这个

这是我的
.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)

(?is)(?在你的情况下,我建议你用另一种方式(逐行解析以提高性能)。正如我所看到的,你只是用替换的文本将文件从输入重写到输出,所以在我看来,在内存中读取整个文件是没有意义的。
如果您不想使用这种方法,请参阅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;
            }
        }
    }
}

需要正则表达式吗?输入文件有多大?@pwas:file有几千行。还有其他更好的方法吗?我看到您正在将整个文件读入内存,替换文本并将其写入输出文件。我认为最好是逐行读取文件:如果只是读取行不是您的注释,则写入输出文件,否则write替换输出。@pwas:谢谢你的想法。有代码示例吗?我已经准备好了代码示例。