Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java replaceAll() method to escape special characters

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");
like image 800
Abhishek Goel Avatar asked Oct 31 '25 07:10

Abhishek Goel


1 Answers

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");
like image 178
Joni Avatar answered Nov 01 '25 19:11

Joni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!