Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple linebreaks

Tags:

java

How can I remove multiple linebreaks from a string so I only get one linebreak if any. For example I have a string with "\r\n\r\n\r\n\r\n\r\n\r\n\r\n", how can I turn that into a single '\n' ?

like image 729
madprops Avatar asked Aug 25 '12 19:08

madprops


People also ask

How do I get rid of new lines in a text file?

Open TextPad and the file you want to edit. Click Search and then Replace. In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text. Check the Regular Expression box.

How do you remove a line break in a string?

Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.


2 Answers

You could use:

myString = myString.replaceAll("[\r\n]+", "\n");
like image 112
Reimeus Avatar answered Sep 23 '22 12:09

Reimeus


In Android I managed to remove more than 2 line breaks with this

textPiece = textPiece.replaceAll("\n\n\n+", "\n\n");
like image 34
Rafael Avatar answered Sep 24 '22 12:09

Rafael