正则表达式替换每个换行符

时间:2013-01-26 20:20:56

标签: c# regex replace newline

我需要用另一个字符(比如'X')替换字符串中的每个换行符。我希望用一个换行符折叠多个换行符!

PS:这个正则表达式用一个换行符取代所有连续的换行符,但它不是我需要的。

Regex regex_newline = new Regex("(\r\n|\r|\n)+");

2 个答案:

答案 0 :(得分:13)

这将用一些东西替换一个或多个换行符,不一定用一个换行符 - 这是由你没有显示的regex_newline.Replace(...)调用决定的。

基本上,答案是

 Regex regex_newline = new Regex("(\r\n|\r|\n)");   // remove the '+'
 // :
 regex_newline.replace(somestring, "X");

答案 1 :(得分:8)

只需使用String.Replace方法并替换字符串中的Environment.NewLine即可。不需要正则表达式。

http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx

相关问题