14

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Jigglypuff
  • 1,433
  • 6
  • 24
  • 38

4 Answers4

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
ironicaldiction
  • 1,200
  • 4
  • 12
  • 27
  • Thank you! It works. Sorry I didn't explain the problem clearly. – Jigglypuff Aug 27 '13 at 17:21
  • 1
    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). – ironicaldiction Aug 27 '13 at 17:27
2

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 org.apache.commons.text.translate.AggregateTranslator;
import org.apache.commons.text.translate.CharSequenceTranslator;
import org.apache.commons.text.translate.LookupTranslator;

public class CustomEscaper {
    
    private static final CharSequenceTranslator ESCAPE_CUSTOM;
    
    static {
        final Map<CharSequence, CharSequence> escapeCustomMap = new HashMap<>();
                    
        escapeCustomMap.put("+" ,"\\+" ); 
        escapeCustomMap.put("-" ,"\\-" ); 
        ...
        escapeCustomMap.put("\\", "\\\\");
        ESCAPE_CUSTOM = new AggregateTranslator(new LookupTranslator(escapeCustomMap));
    }

    public static final String customEscape(final String input) {
        return ESCAPE_CUSTOM.translate(input);
    }
}
cquezel
  • 3,859
  • 1
  • 30
  • 32
1

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
Rahul Sharma
  • 5,614
  • 10
  • 57
  • 91
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("\"","\\\\\"");

Shaheaz
  • 23
  • 5