How can I add escape characters to a Java String?
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
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);
}
}