Indigo
Indigo

Reputation: 2997

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

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.

Upvotes: 11

Views: 52771

Answers (3)

MadConan
MadConan

Reputation: 3777

Oh sure, you could do it with one line of regex, but what fun is that?

public static String fixToNewline(String orig){
    char[] chars = orig.toCharArray();
    StringBuilder sb = new StringBuilder(100);
    for(char c : chars){
        switch(c){
            case '\r':
            case '\f':
                break;
            case '\n':
                sb.append("\\n");
                break;
            default:
                sb.append(c);
        }
    }
    return sb.toString();
}

public static void main(String[] args){
   String s = "This is \r\n a String with \n Different Newlines \f and other things.";

   System.out.println(s);
   System.out.println();
   System.out.println("Now calling fixToNewline....");
   System.out.println(fixToNewline(s));

}

The result

This is 
 a String with 
 Different Newlines  and other things.

Now calling fixToNewline....
This is \n a String with \n Different Newlines  and other things.

Upvotes: 2

Alper
Alper

Reputation: 601

This seems to work well:

String s = "This is a String\nand all newline chars\nshould be replaced in this example.";
System.out.println(s);
System.out.println(s.replaceAll("[\\n\\r]+", "\\\\n"));

By the way, you don't need to catch exception.

Upvotes: 3

anubhava
anubhava

Reputation: 784898

If you want literal \n then following should work:

String repl = str.replaceAll("(\\r|\\n|\\r\\n)+", "\\\\n")

Upvotes: 30

Related Questions