Java Utililty Methods String Escape

List of utility methods to do String Escape

Description

The list of methods to do String Escape are organized into topic(s).

Method

StringaddEscape(String a_unescaped)
Add escape characters (\) before each of the characters to escape and each of the escape characters themselves.
String escaped = null;
if (null != a_unescaped) {
    StringBuffer text = new StringBuffer();
    char charToEscape = ',';
    char character;
    int length = a_unescaped.length();
    for (int index = 0; index < length; index++) {
        character = a_unescaped.charAt(index);
...
StringaddEscapeCapacityToRegex(String inputRegex)
This will encode the given Regex string the capacity to ignore the escaped word, i.e.
return String.format("(?<!%1$s)%2$s", ESCAPE_CHARACTER, inputRegex);
StringaddEscapeChar(String str)

Description:Convert string which contains '%','_' to '\%' and '\_'

String output = str.replaceAll("%", "\\\\" + "%");
output = output.replaceAll("_", "\\\\" + "_");
return output;
StringaddEscapeCharactersForSpaces(String s)
add Escape Characters For Spaces
String outputString = "";
for (int i = 0; i < s.length(); ++i) {
    if (s.charAt(i) == ' ')
        outputString = outputString.concat("\\");
    outputString = outputString.concat(s.substring(i, i + 1));
return outputString;
StringaddEscapeCharsToBackSlash(String code)
Adds escape characters to all occurences of \.
if (code == null) {
    code = "";
return code.replace("\\", "\\\\");
StringaddEscapes(String s)
add Escapes
s = s.replace("\r", "\\r");
s = s.replace("\n", "\\n");
return s = s.replace("\"", "\\\"");
StringaddEscapes(String str)
Replaces unprintable characters by their espaced (or unicode escaped) equivalents in the given string.
StringBuilder sb = new StringBuilder();
char ch;
for (int i = 0; i < str.length(); i++) {
    switch (str.charAt(i)) {
    case 0:
        continue;
    case '\b':
        sb.append("\\b");
...
StringaddEscapeSequence(String inputStr)
add Escape Sequence
if (inputStr.contains("\\")) {
    inputStr = inputStr.replace("\\", "\\\\");
if (inputStr.contains("\'")) {
    inputStr = inputStr.replace("\'", "\\\'");
if (inputStr.contains("\"")) {
    inputStr = inputStr.replace("\"", "\\\"");
...
StringaddEscapesToCode(String code)
Adds escape characters to all occurences of ", \ and \n.
code = addEscapeCharsToBackSlash(code);
code = addEscapeNewLinesToCode(code);
return addEscapeCharsToCode(code);
StringaddEscChar(String str)
add Esc Char
return str.replace("'", "\'");