Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java escaping escape sequence

I want to escape escape sequences in a string.

Example: if I had a string whose contents were "\n\u0073", I need to escape them in such a way that if I printed it to the command line, I would see

this:
\n\u0073
instead of:

s

I'll also be escaping double quotes (") and backslashes (\), and I figured out an expression to escape those already:

Pattern p = Pattern.compile("([\"\\\\])");
String str = p.matcher("\"\n\u0073\\"").replaceAll("\\\\$1");

This yields me:

\"
s\\

It doesn't take care of the escape sequences, though. What I want is:

\"\n\u0073\\

What modifications do I need to make to escape the escape sequences?

like image 208
dawsonc623 Avatar asked Oct 06 '22 16:10

dawsonc623


1 Answers

You may use the StringEscapeUtils. There is method escapeJava() on it. Unfortunately, imo, there is no way to escape unicode literals like \u0073 so for your example input "\"\n\u0073\"", StringEscapeUtils.escapeJava("\"\n\u0073\"") will return \"\ns\"

like image 168
Jiri Kremser Avatar answered Oct 10 '22 01:10

Jiri Kremser