C# Remove first line of text if it's empty and or replace first line with another string if first line contain string

Tub Ntxawg Yaaj 121 Reputation points
2020-12-03T08:11:28.45+00:00

I tried to do some research and could not find a solution for this.

Here is my simple text:

save[0] = 0

generate_num[0] = 1
  1. My expectation is to check the first line, if it's blank then remove the first line so the save[0] = [num] now should be in first line.
    save[0] = 0 generate_num[0] = 1
  2. Next, I need to replace any int after the equal sign '=' for the first line only. Because the int is random, we cannot tell if it'll always be 0. I do not want to replace the string from other lines, but the first only. Ex: save[0] = 25 generate_num[0] = 1

The reason the integer for save[0] is not constant because when you close the program after you save it; it loses its place of how many times the text file has been saved.

Starting codes:

        //delete first line if empty
        string[] Reread = File.ReadAllLines(path);

        int gogetnum = Convert.ToInt32(numbers) + 2; //This will determine my next number for the random save integer.
Developer technologies | Visual Studio | Other
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2020-12-03T09:19:43.96+00:00

    Check an approach:

    string text = @"  
      
    save[0] = 0  
          
    generate_num[0] = 1  
    ";  
      
    string result = Regex.Replace( text, @"(?<=^\s*.+?=\s*)(\d+)", "25" );  
    

    To increase the found number:

    string result = Regex.Replace( text, @"(?<=^\s*.+?=\s*)(\d+)", m => ( int.Parse( m.Value ) + 2 ).ToString( ) );  
    

    To read and write the file, use File.ReadAllText and File.WriteAllText.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.