Benjy Kessler
Benjy Kessler

Reputation: 7616

Escaping characters in a string

I have a string that contains escaped characters:

String myString = "I\\nam\\na\\nmultiline\\nstring\\twith\\ttabs";

I would like to convert the escaped characters so that it would output:

System.out.println(myConvertedString);
I
am
a
multiline
string    with    tabs

Is there any standard function (maybe Guava) that does this?

Upvotes: 1

Views: 902

Answers (2)

MaxPower
MaxPower

Reputation: 871

StringEscapeUtils in the apache commons library has many methods that will escape, or unesecape a string as required.

StringEscapeUtils.escapeJava(someString);
StringEscapeUtils.unescapeJava(someOtherString);

Upvotes: 1

assylias
assylias

Reputation: 328568

If you have received the exception from a stack trace, the only escaped characters are probably \n and \t, in which case:

String converted = input.replace("\\n", "\n").replace("\\t", "\t");

If there can be more than that I think you'll have to list all the possibilities.

Upvotes: 1

Related Questions