简体   繁体   中英

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.

here is my .txt file

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 . Here is the C# code im gonna use with regular expression.

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

So my question is what is the regular expression ( [pattern] ) I can uses here?

尝试:

(?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.

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;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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