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?

13
  • 1
    what??? what do you get if you print the "non scaped string"?? Commented Jun 26, 2017 at 16:58
  • What do you mean? Commented Jun 26, 2017 at 16:58
  • you have this : String foo = "I\nam\na\nmultiline\nstring\twith\ttabs"; Commented Jun 26, 2017 at 16:59
  • 2
    So, Call a string replace and replace every occurrence of "\\" with "\" Commented Jun 26, 2017 at 17:01
  • 3
    Possible duplicate of How to unescape a Java string literal in Java?. But it depends. Is that a Java-escaped string? Or JavaScript? Or C? Or some other language? They are all mostly the same, but there are differences. Commented Jun 26, 2017 at 17:03

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, unfortunately I can't use Apache commons in my project but this looks good.
@BenjyKessler is it? Do you have a source?
as of 3.6, use commons-text StringEscapeUtils instead, so they want you to use a different package
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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.