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?
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\"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With