Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add escape characters to a Java String?

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?

like image 624
Jigglypuff Avatar asked Aug 27 '13 17:08

Jigglypuff


People also ask

How do you add an escape character to a string?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

How do you escape an escape character in Java?

In Java, if a character is preceded by a backslash (\) is known as Java escape sequence or escape characters. It may include letters, numerals, punctuations, etc. Remember that escape characters must be enclosed in quotation marks (""). These are the valid character literals.

Can you add character to a string Java?

Insert a character at the beginning of the String using the + operator. Insert a character at the end of the String using the + operator.


2 Answers

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
like image 92
ironicaldiction Avatar answered Sep 17 '22 10:09

ironicaldiction


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);
    }
}
like image 21
cquezel Avatar answered Sep 19 '22 10:09

cquezel