-1

Question above.

And by 'unescaped' I mean "Hello \\n \\\"World\\\"".

String myString = "Hello \\n \\\"World\\\"";
System.out.println("Before : \n");
System.out.println(myString);
String myConverted = escape(myString);
System.out.println("After : \n");
System.out.println(myConverted);

Output:

Before :

Hello \n \"World\"
After :

Hello
 "World"

So I would be converting it to "Hello \n \"World\"".

I want it to escape the characters.

Is there a function to do this? escape is only an example.

8
  • P.S, I dont know the term to unescaped strings, and I dont want to use generic replace methods, I want to escape any supposing escape characters. Commented Dec 5, 2023 at 20:46
  • 4
    There isn't, and, you've got your terms mixed up. Your input string is 'escaped', and that method should be called 'unescape'. The concept of a 'backslash-n' is called an 'escape'; hence, turning a string containing a newline into a string containing backslash + n is 'escaping' it, and the reverse is 'unescaping' it. Note that this sounds like an X/Y problem. For example, you used regexes to parse a string out of some JSON. The real solution is to use a JSON library, not to try to write your own unescaper. There is no such method in core java. Commented Dec 5, 2023 at 20:57
  • @rzwitserloot ok, the java suceks, I give up on using it... Commented Dec 5, 2023 at 21:00
  • 4
    since Java 15: String myConverted = myString.translateEscapes(); - documentation (which can be searched) Commented Dec 5, 2023 at 21:07
  • 1
    "the java suceks, I give up on using it." -- somehow I think Java will not suffer because of this. Commented Dec 5, 2023 at 23:03

1 Answer 1

1

You are using too much \s. To make new line you need \n, to make " will do \". Place 3 of \\\" and you get one \ escaped before escaped " Therefre if you generate this data it need some adjust. If you recieving it this way, unfortunately you have to make some rules of processing. Hovever since 15 java there is easy way:

    String myString = "Hello \\n \\\"World\\\"";
    System.out.println("Before : \n");
    String s = myString.translateEscapes();
    System.out.println("s = " + s);
Sign up to request clarification or add additional context in comments.

2 Comments

No need for String::replace, just use String::translateEscapes.
You helped the development of the programming language Luca! Thank you!

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.