简体   繁体   English

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

[英]Replace the content between specific two text lines in a text file using regular expression

I need to replace the content in a text file between specific two lines. 我需要在特定的两行之间替换文本文件中的内容。 So I'm planing to use reguler expression for this. 所以我打算为此使用reguler表达式。

here is my .txt file 这是我的.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

I need to replace the content between //DYNAMIC-CONTENT-START and //DYNAMIC-CONTENT-END . 我需要在//DYNAMIC-CONTENT-START//DYNAMIC-CONTENT-END之间替换内容。 Here is the C# code im gonna use with regular expression. 这是正则表达式将使用的C#代码。

File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement"));

So my question is what is the regular expression ( [pattern] ) I can uses here? 所以我的问题是我在这里可以使用什么正则表达式( [pattern] )?

尝试:

(?is)(?<=//DYNAMIC-CONTENT-START).*?(?=//DYNAMIC-CONTENT-END)

In your case I suggest you do in other way (parsing line by line to imporve performance). 对于您的情况,我建议您采用其他方式(逐行分析以提高性能)。 As I can see you are rewriting file from input to output only with replaced text, so in my opinion reading whole while into memory has no sense. 如我所见,您仅使用替换的文本将文件从输入重写为输出,因此我认为将整个过程读入内存是没有意义的。 If you don't want use this approach, see Tim Tang answer. 如果您不想使用这种方法,请参见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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM