Search code examples
c#textreplacetexttrimming

Delete all text file content except one string chosen with C#


I have this txt file:

********** Welcome to file*********************This test file.It can gives value.It returns if the validation is successful or shows errors where the XML validation fails.It checks for syntax and content as well.****************************************************************2022-07-14 20:07:54,730 [INFO] textvalue- text has been generated successfully2022-07-14 20:07:54,731 [INFO] neededvalue - *** value needed = ARdBaG1lZCBNb2hhbWVkIEFMIEFobWFkeQIPMzAwMDc1NTg4NzAwM==

but these values 2022-07-14 20:07:54,730 and 2022-07-14 20:07:54,731 are changeable and want to remove all text except this value ARdBaG1lZCBNb2hhbWVkIEFMIEFobWFkeQIPMzAwMDc1NTg4NzAwM== what ever the changeable values are changed!

I trying this code :

string remove = "********** Welcome to file*********************This test file.It can gives value.It returns if the validation is successful or shows errors where the XML validation fails.It checks for syntax and content as well.****************************************************************2022-07-14 20:07:54,730 [INFO] textvalue- text  has been generated successfully2022-07-14 20:07:54,731 [INFO] neededvalue -  *** value needed = ";
            
            var text2 = "";
            string resultt = string.Empty;
            var lines = File.ReadAllLines(@"D:\text.txt");
            foreach (var line in lines)
            {

                if (line.Contains(remove))
                {
                    text2 = line.Replace(remove, "");
                    resultt = text2.Trim();
                }
            }
            Console.WriteLine(text2);
            Console.ReadLine();

it gives me the value but when the changeable values are changes then the remove string not matches!


Solution

  • Use regex to match content after "value needed = ". Then it shouldn't matter what comes before.

    A good pattern would be:

    "(?<=value needed = ).+"
    

    Which translates to:

    • (?<=value needed = ): look for the term "value needed = " before some text
    • .+: match any character that occurs any number of times.

    Here is it's use in C#:

    string text = "etc, etc, etc. ... value needed = ARdBaG1lZCBNb2hhbWVkIEFMIEFobWFkeQIPMzAwMDc1NTg4NzAwM==";
            
    var regex = new Regex("(?<=value needed = ).+");
    Console.WriteLine(regex.Match(text)?.Value);
    // ARdBaG1lZCBNb2hhbWVkIEFMIEFobWFkeQIPMzAwMDc1NTg4NzAwM==