且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用c#将多个enter(\ n\ n)替换为单个输入在richtextbox中的\ n

更新时间:2023-02-23 13:43:33

您可以使用 Regex [ ^ ] 。

假设按钮点击事件有2个富文本框:richTextBox1和richTextBox2以及一个按钮

,添加:

You may use Regex[^].
Say there are 2 richtextboxes: richTextBox1 and richTextBox2 and a button
on the button click event, add this:
string txt1 = richTextBox1.Text;
var pattern = "(\\n){2,}";
var replacePattern = "\n";
richTextBox2.Text =  Regex.Replace(txt1, pattern, replacePattern, RegexOptions.IgnoreCase);


在Windows上,新行是 \\\\ n - CRLF 但在基于Unix的系统上,换行符为 \ n - LF 。这可能是您需要更换的东西之一。



Windows保持程序运行的平台的换行格式为 System。 Environment.NewLine



如果您不介意使用正则表达式。您可以在这两个平台上的一次传递中删除多行,例如:


On Windows, a new line is \r\n - CRLF but on Unix based systems, a newline is \n - LF. That could be one of the things you needed to replace.

Windows keeps the newline format of the platform your program is running in at System.Environment.NewLine

And if you don't mind using Regex. You could remove multiple lines in a single pass on both platforms like this

string formatted = Regex.Replace(rtxtTypeing.Text, @"(?:\r\n|\r(?!\n)|(?!<\r)\n){2,}", System.Environment.NewLine);









用一个br替换多个换行符 [ ^ ]



替换字符串中的换行符 [ ^ ]