StringEscapeHelper { public String unescape(String str) { int slashIndex = str.indexOf('\\'); if (slashIndex > -1) { int offset = 0; StringBuilder unescaped = new StringBuilder(str.length() - 1); while (slashIndex > -1) { char c = str.charAt(slashIndex + 1); char r = (c < unescapeMap.length) ? unescapeMap[c] : NO_REPLACEMENT; if (r != NO_REPLACEMENT) { unescaped.append(str, offset, slashIndex); unescaped.append(r); offset = slashIndex + 2; } else if (unescapeUnicodeEscapes && c == 'u') { String hexCode = str.substring(slashIndex + 2, slashIndex + 6); String replacement = new String(Character.toChars(Integer.parseInt(hexCode, 16))); unescaped.append(str, offset, slashIndex); unescaped.append(replacement); offset = slashIndex + 6; } slashIndex = str.indexOf('\\', slashIndex + 2); } unescaped.append(str, offset, str.length()); return unescaped.toString(); } else { return str; } } StringEscapeHelper(char... replacementPairs);  StringEscapeHelper(boolean unescapeUnicodeEscapes, char... replacementPairs); String unescape(String str); String escape(String str);  }
@Test public void nothingIsUnescapedByDefault() { StringEscapeHelper escapeHelper = new StringEscapeHelper(false); String unescaped = escapeHelper.unescape("hello\\u0020world\\n"); assertThat(unescaped, is("hello\\u0020world\\n")); }
@Test public void unicodeEscapesCanBeUnescaped() { StringEscapeHelper escapeHelper = new StringEscapeHelper(true); String unescaped = escapeHelper.unescape("hello\\u0020world\\u000a"); assertThat(unescaped, is("hello world\n")); }
@Test public void escapesAreReplacedByTheirReplacements() { StringEscapeHelper escapeHelper = new StringEscapeHelper( 'n', '\n', 't', '\t', 'x', '!' ); String unescaped = escapeHelper.unescape("\\thello\\nworld\\x"); assertThat(unescaped, is("\thello\nworld!")); }