Java replaceAll() method to escape special characters

Abhishek Goel picture Abhishek Goel · Aug 12, 2013 · Viewed 13.5k times · Source

I am using java replaceAll() method to escape new line characters

String comment = "ddnfa \n  \r \tdnfadsf ' \r t  ";
comment = comment.replaceAll("(\\n|\\r|\\t)","\\\\$1");
System.out.println(comment);

But the above code is still inserting new line.

Is there a way to output the comment exactly the same (i.e. with \n and \r instead of inserting new line)?

UPDATE:

I ended up using:

comment = comment.replaceAll("\\n","\\\\n")
                 .replaceAll("\\r","\\\\r")
                 .replaceAll("\\t","\\\\t");

Answer

Joni picture Joni · Aug 12, 2013

You'll have to go one-by-one, since the new-line character U+000A has nothing to do with the two-character escape sequence \n:

comment = comment.replaceAll("\n","\\\\n");
comment = comment.replaceAll("\r","\\\\r");
comment = comment.replaceAll("\t","\\\\t");