1

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?

assylias
  • 321,522
  • 82
  • 660
  • 783
Benjy Kessler
  • 7,356
  • 6
  • 41
  • 69

2 Answers2

1

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • This will work for my use case but I thought there might be a more generic solution. It's surprising that this doesn't exist since the code clearly exists within the Java compiler. – Benjy Kessler Jun 26 '17 at 17:11
1

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

StringEscapeUtils.escapeJava(someString);
StringEscapeUtils.unescapeJava(someOtherString);
MaxPower
  • 881
  • 1
  • 8
  • 25