规范化在C#中的换行符 [英] Normalize newlines in C#

查看:125
本文介绍了规范化在C#中的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可能包含一个数据流\ r,\ n,即\ r \ n,即\ñ\ R或它们的任意组合。有一个简单的方法来将数据标准化,使所有的人简直成了\ r \ n对,使显示更一致?

这样的东西,会产生转换表的这样的:

  \ r  - > \ r \ñ
\ N  - > \ r \ñ
\ñ\ N  - > \ r \ñ\ r \ñ
\ñ\ r  - > \ r \ñ
\ r \ N  - > \ r \ñ
\ r \ñ\ N  - > \ r \ñ\ r \ñ
 

解决方案

我相信这将做什么,你需要:

 使用System.Text.RegularEx pressions;
// ...
串规范化= Regex.Replace(originalString,@\ r \ N | \ñ\ r | \ N | \ R,\ r \ N);
 

我不是100%确定确切的语法,而我没有的.Net编译器方便的检查。我在Perl写的,并转化成(希望正确)C#。唯一真正的关键是要匹配\ r \ n和\ñ\ r之首。

要应用到整个流,只是在输入块运行研究。 (你可以用,如果你想有一个流包装做到这一点。)


原perl的:

  $海峡=〜S / \ r \ N | \ñ\ r | \ N | \ r / \ r \ N /克;
 

测试结果:

  [bash的$] ./test.pl
\ r  - > \ r \ñ
\ N  - > \ r \ñ
\ñ\ N  - > \ r \ñ\ r \ñ
\ñ\ r  - > \ r \ñ
\ r \ N  - > \ r \ñ
\ r \ñ\ N  - > \ r \ñ\ r \ñ
 


更新:现在转换\ñ\ r以\ r \ n,即虽然我不认为这是标准化

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\n pairs to make display more consistent?

So something that would yield this kind of translation table:

\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

解决方案

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.

这篇关于规范化在C#中的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆