Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace all NewLine or BreakLine characters with \n in a String - Platform independent

Tags:

java

string

regex

I am looking for a proper and robust way to find and replace all newline or breakline chars from a String independent of any OS platform with \n.

This is what I tried, but didn't really work well.

public static String replaceNewLineChar(String str) {
    try {
        if (!str.isEmpty()) {
            return str.replaceAll("\n\r", "\\n")
                    .replaceAll("\n", "\\n")
                    .replaceAll(System.lineSeparator(), "\\n");
        }
        return str;
    } catch (Exception e) {
        // Log this exception
        return str;
    }
}

Example:

Input String:

This is a String
and all newline chars 
should be replaced in this example.

Expected Output String:

This is a String\nand all newline chars\nshould be replaced in this example.

However, it returned the same input String back. Like it placed \n and interpreted it as Newline again. Please note, if you wonder why would someone want \n in there, this is a special requirement by user to place the String in XML afterwords.

like image 984
Indigo Avatar asked Nov 11 '13 15:11

Indigo


People also ask

Can we use \n in string?

Adding Newline Characters in a String In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you replace a new line in a string in Java?

Line Break: A line break (“\n”) is a single character that defines the line change. In order to replace all line breaks from strings replace() function can be used.

What is the equivalent of \n in Java?

\n and 0xa are exactly the same thing.

How do you remove all new lines from a string in Python?

Use str. replace() to remove all line breaks from a string Call str. replace(old, new) where old is "\n" and new is " " to replace the line breaks with a single space.


1 Answers

If you want literal \n then following should work:

String repl = str.replaceAll("(\\r|\\n|\\r\\n)+", "\\\\n")
like image 112
anubhava Avatar answered Oct 29 '22 22:10

anubhava