Replace "newline" char with regex in C #

I want to find each line in a text file that contains the sequence “letter or number”, “new line”, “letter or number”, and then replace “new line” with “space”.

This is what I have tried so far:

private void button3_Click(object sender, EventArgs e)
{
     string pathFOSE = @"D:\Public\temp\FOSEtest.txt";     
     string output = Regex.Replace(pathFOSE, @"(?<=\w)\n(?=\w)", " ");                      

     string pathNewFOSE = @"D:\Public\temp\NewFOSE.txt";
     if (!System.IO.File.Exists(pathNewFOSE))
     {
          // Create a file to write to. 
          using (System.IO.StreamWriter sw = System.IO.File.CreateText(pathNewFOSE))
          {                
          }
     File.AppendAllText(pathNewFOSE, output);
     }
}

But my whole program creates a new text file containing only this line "D:\Public\temp\FOSEtest.txt"

Any idea what is going on? Also is there a \nproper way to search for newlines in a text file in Windows7? Thanks

Change . I made the changes suggested by Avinash and added that I am working on Windows 7.

2. , , Replace , , , .

Final Edit: stribizhev, . , !

+4
2

Windows \r\n ( + ). , , -

string output = Regex.Replace(pathFOSE, @"(?<=\w)\r\n(?=\w)", " ");

, \w Unicode . ( ),

string output = Regex.Replace(pathFOSE, @"(?i)(?<=[a-z0-9])\r\n(?=[a-z0-9])", " ");

,

string output = Regex.Replace(pathFOSE, @"(?i)(?<=[a-z0-9])(?:\r\n|\n|\r)(?=[a-z0-9])", " ");

, + quantifier (?:\r\n|\n|\r)+.

, .

var pathFOSE = @"D:\Public\temp\FOSEtest.txt";
var contents = File.ReadAllText(pathFOSE);
var output = Regex.Replace(contents, @"(?i)(?<=[a-z0-9])(?:\r\n|\n|\r)(?=[a-z0-9])", " ");

var pathNewFOSE = @"D:\Public\temp\NewFOSE.txt";
if (!System.IO.File.Exists(pathNewFOSE))
{
    File.WriteAllText(pathNewFOSE, output);
}
+3

lookbehind.

Regex.Replace(pathFOSE, @"(?<=\w)\n(?=\w)", " "); 
                            ^

(?=\w) , , .

Regex.Replace(pathFOSE, @"(?<=\w)[\r\n]+(?=\w)", " "); 
+4

All Articles