Click here to Skip to main content
15,892,072 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi everybody,

I have an richtextbox in which user enter a passage but when user enter multiple enter (\n\n\n) then I want to replace it into single \n but i do not know how this possible.

I have replace multiple space into single space using lambda expression

var list = rtxtTypeing.Text.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
rtxtTypeing.Text = string.Join(" ", list);

and same thing i want to use in to replace multiple \n\n\n into single enter \n

var list3 = rtxtTypeing.Text.Split('\n').Where(s => !string.IsNullOrWhiteSpace(s));
rtxtTypeing.Text = string.Join("\n", list3);

but it is not working.

Please help me where I am wrong.

Thanks
Ram Kumar
Posted
Updated 13-Feb-23 3:28am
Comments
BillWoodruff 24-Jan-15 5:32am    
Do you mean that you want to prevent the user from entering multiple return AS THEY TYPE ?

You may use Regex[^].
Say there are 2 richtextboxes: richTextBox1 and richTextBox2 and a button
on the button click event, add this:
C#
string txt1 = richTextBox1.Text;
var pattern = "(\\n){2,}";
var replacePattern = "\n";
richTextBox2.Text =  Regex.Replace(txt1, pattern, replacePattern, RegexOptions.IgnoreCase);
 
Share this answer
 
v2
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

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



See
Replace multiple line breaks with a single br[^]

Replace line breaks in a string[^]
 
Share this answer
 
v2
You can try this, it worked for me.

RichTextBox1.Rtf=RichTextBox1.Rtf.Replace("\\\\n", @"\line");
 
Share this answer
 
Comments
Dave Kreskowiak 13-Feb-23 10:42am    
You failed to understand the question. Also, I doubt the OP is still looking for a solution 8 years later.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900