Normalize newlines in C#

前端 未结 8 2052
滥情空心
滥情空心 2020-12-03 06:48

I have a data stream that may contain \\r, \\n, \\r\\n, \\n\\r or any combination of them. Is there a simple way to normalize the data to make all of them simply become \\r

8条回答
  •  無奈伤痛
    2020-12-03 07:25

    I believe this will do what you need:

    using System.Text.RegularExpressions;
    // ...
    string normalized = Regex.Replace(originalString, @"\r\n|\n\r|\n|\r", "\r\n");
    

    I'm not 100% sure on the exact syntax, and I don't have a .Net compiler handy to check. I wrote it in perl, and converted it into (hopefully correct) C#. The only real trick is to match "\r\n" and "\n\r" first.

    To apply it to an entire stream, just run in on chunks of input. (You could do this with a stream wrapper if you want.)


    The original perl:

    $str =~ s/\r\n|\n\r|\n|\r/\r\n/g;
    

    The test results:

    [bash$] ./test.pl
    \r -> \r\n
    \n -> \r\n
    \n\n -> \r\n\r\n
    \n\r -> \r\n
    \r\n -> \r\n
    \r\n\n -> \r\n\r\n
    

    Update: Now converts \n\r to \r\n, though I wouldn't call that normalization.

提交回复
热议问题