How can I add escape characters to a Java String?
Asked Answered
P

4

15

If I had a string variable:

String example = "Hello, I'm here";

and I wanted to add an escape character in front of every ' and " within the variable (i.e. not actually escape the characters), how would I do that?

Pickford answered 27/8, 2013 at 17:3 Comment(6)
You mean in an editor?Ostraw
Just type the \ character?Scrupulous
Use StringEscapeUtils.html#escapeJava from apache commonsTowel
I mean using the example variable.Pickford
possible duplicate of Escape double quotes in JavaKandicekandinsky
example.replace("'", "\\'");Ostraw
P
21

I'm not claiming elegance here, but i think it does what you want it to do (please correct me if I'm mistaken):

public static void main(String[] args)
{
    String example = "Hello, I'm\" here";
    example = example.replaceAll("'", "\\\\'");
    example = example.replaceAll("\"", "\\\\\"");
    System.out.println(example);
}

outputs

Hello, I\'m\" here
Pirzada answered 27/8, 2013 at 17:15 Comment(2)
Thank you! It works. Sorry I didn't explain the problem clearly.Pickford
Glad to help...in the future, realize that when talking about escaping characters, most people DON'T want to see a backslash in their code. What you asked for is quite unusual. Be sure to be super precise if deviating from what is typically done with in a given programming subject (e.g. escape characters).Pirzada
T
3

Try Apache Commons Text library-

    System.out.println(StringEscapeUtils.escapeCsv("a\","));
    System.out.println(StringEscapeUtils.escapeJson("a\","));
    System.out.println(StringEscapeUtils.escapeEcmaScript("Hello, I'm \"here"));

Result:

"a"","
a\",
Hello, I\'m \"here
Trutko answered 9/7, 2020 at 0:9 Comment(0)
N
3

For others who get here for a more general escaping solution, building on Apache Commons Text library you can build your own escaper. Have a look at StringEscapeUtils for examples:

import java.util.Map;

import org.apache.commons.text.translate.CharSequenceTranslator;
import org.apache.commons.text.translate.LookupTranslator;

public final class CustomEscaper {  

    private static final CharSequenceTranslator CUSTOM_ESCAPER = 
        new LookupTranslator(
            Map.of(
                "+" , "\\+",
                "-" , "\\-",
                // ...
                "\\", "\\\\"
            )
    );
    
    private CustomEscaper() {
        // hide
    }

    public static final String escape(String input) {
        return CUSTOM_ESCAPER.translate(input);
    }
}
Night answered 5/8, 2020 at 15:57 Comment(0)
R
0

If it is only one quote then easy but if it is double quote then use like this

eachClientName = eachClientName.replaceAll("'","\\\'");

eachClientName =eachClientName.replaceAll("\"","\\\\\"");

Remainderman answered 4/8, 2023 at 11:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.