[Q#18471500][A#18471715] How can I add escape characters to a Java String?
https://stackoverflow.com/q/18471500
If I had a string variable: 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?
Answer
https://stackoverflow.com/a/18471715
I'm not claiming elegance here, but i think it does what you want it to do (please correct me if I'm mistaken): outputs
APIzation
public static void main(String[] args)
{
String example = "Hello, I'm\" here";
example = example.replaceAll("'", "\\\\'");
example = example.replaceAll("\"", "\\\\\"");
System.out.println(example);
}
Hello, I\'m\" here
package com.stackoverflow.api;
public class Human18471715 {
public static String addEscapeCharacters(String example) {
// String example = "Hello, I'm\" here";
example = example.replaceAll("'", "\\\\'");
example = example.replaceAll("\"", "\\\\\"");
return example;
}
}
package com.stackoverflow.api;
/**
* How can I add escape characters to a Java String?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/18471715">https://stackoverflow.com/a/18471715</a>
*/
public class APIzator18471715 {
public static String addCharacter(String example) {
example = example.replaceAll("'", "\\\\'");
example = example.replaceAll("\"", "\\\\\"");
return example;
}
}