如何在c#中替换字符串中的换行符?


当前回答

由于新行可以用\n, \r和\r\n来分隔,首先我们将\r和\r\n替换为\n,然后才分割数据字符串。

下面的代码行应该进入parseCSV方法:

function parseCSV(data) {
    //alert(data);
    //replace UNIX new lines
    data = data.replace(/\r\n/g, "\n");
    //replace MAC new lines
    data = data.replace(/\r/g, "\n");
    //split into rows
    var rows = data.split("\n");
}

其他回答

如果你想“清除”新行,flamebaud注释使用regex @“[\r\n]+”是最好的选择。

using System;
using System.Text.RegularExpressions;

class MainClass {
  public static void Main (string[] args) {
    string str = "AAA\r\nBBB\r\n\r\n\r\nCCC\r\r\rDDD\n\n\nEEE";

    Console.WriteLine (str.Replace(System.Environment.NewLine, "-"));
    /* Result:
    AAA
    -BBB
    -
    -
    -CCC


    DDD---EEE
    */
    Console.WriteLine (Regex.Replace(str, @"\r\n?|\n", "-"));
    // Result:
    // AAA-BBB---CCC---DDD---EEE

    Console.WriteLine (Regex.Replace(str, @"[\r\n]+", "-"));
    // Result:
    // AAA-BBB-CCC-DDD-EEE
  }
}
string s = Regex.Replace(source_string, "\n", "\r\n");

or

string s = Regex.Replace(source_string, "\r\n", "\n");

这取决于你想走哪条路。

希望能有所帮助。

不要忘记replace不会在字符串中进行替换,而是返回一个替换了字符的新字符串。下面将删除换行符(而不是替换它们)。如果用其他方法替换它们,我将使用@Brian R. Bondy的方法,可能包装为扩展方法。记住,在调用Replace或提供的扩展方法之前,首先检查空值。

string line = ...

line = line.Replace( "\r", "").Replace( "\n", "" );

作为扩展方法:

public static class StringExtensions
{
   public static string RemoveLineBreaks( this string lines )
   {
      return lines.Replace( "\r", "").Replace( "\n", "" );
   }

   public static string ReplaceLineBreaks( this string lines, string replacement )
   {
      return lines.Replace( "\r\n", replacement )
                  .Replace( "\r", replacement )
                  .Replace( "\n", replacement );
   }
}

安全替换换行符的最好方法是

yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n")             //handling mac linebreaks

这将产生一个只有\n(如换行)作为换行符的字符串。 这段代码对于修复混合换行也很有用。

这是一个非常冗长的单行解决方案,但它是我发现的唯一一个工作,如果你不能使用特殊字符转义,如“\r”和“\n”和\x0d和\u000D以及System.Environment.NewLine作为参数的replace()方法

MyStr.replace(  System.String.Concat( System.Char.ConvertFromUtf32(13).ToString(), System.Char.ConvertFromUtf32(10).ToString() ), ReplacementString  );

这有点离题了,但是为了让它在Visual Studio的XML .props文件中工作,这些文件通过XML属性调用. net,我必须像下面所示那样对它进行修饰。 Visual Studio XML—> . net环境只是不接受特殊字符转义,如“\r”和“\n”以及\x0d和\u000D以及System.Environment.NewLine作为replace()方法的参数。

$([System.IO.File]::ReadAllText('MyFile.txt').replace( $([System.String]::Concat($([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString()))),$([System.String]::Concat('^',$([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString())))))