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


当前回答

如果您的代码应该在不同的环境中运行,我会考虑使用Environment。NewLine常量,因为它是特定环境中使用的换行符。

line = line.Replace(Environment.NewLine, "newLineReplacement");

但是,如果您从另一个系统上的文件中获取文本,这可能不是正确的答案,您应该替换为在另一个系统上使用的任何换行常数。它通常是\n或\r\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())))))

为了确保所有可能的换行方式(Windows, Mac和Unix)都被替换,您应该使用:

string.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\n', 'replacement');

按照这个顺序,当你发现一些行尾字符的组合时,不要使用额外的换行符。

到目前为止发布的解决方案要么只替代Environment。如果替换字符串包含换行符,则会失败,因为它们调用string。多次替换。

下面是一个解决方案,它使用正则表达式在一次字符串传递中完成所有三个替换。这意味着替换字符串可以安全地包含换行符。

string result = Regex.Replace(input, @"\r\n?|\n", replacementString);

如果你想“清除”新行,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
  }
}

基于@mark-bayers的答案和更清晰的输出:

string result = Regex.Replace(ex.Message, @"(\r\n?|\r?\n)+", "replacement text");

它删除了\r\n, \n和\r,而偏爱较长的一个,并将多次出现简化为一次。