StringUtil { public static String unescape(String literal, String escapedChars) { char c = '?'; int i = 0; if (null == escapedChars) { escapedChars = "\\'"; } if (null == literal) { return null; } int len = literal.length(); if (len == 1 && literal.charAt(0) == '\\') { return null; } if (len > 1 && literal.charAt(len - 2) != '\\' && literal.charAt(len - 1) == '\\') { return null; } StringBuilder sb = new StringBuilder(len + 16); for (i = 0; i < len; i++) { c = literal.charAt(i); if (c == '\\') { char escChar = literal.charAt(i + 1); boolean matched = false; for (int j = 0; j < escapedChars.length(); j++) { if (escChar == escapedChars.charAt(j)) { sb.append(escChar); ++i; matched = true; break; } } if (!matched) { return null; } } else { sb.append(literal.charAt(i)); } } return sb.toString(); } private  StringUtil(); static String unescape(String literal, String escapedChars);  }
@Test public void testUnescape() { String s = "abc"; String res = StringUtil.unescape(s, null); assertEquals("abc", res); s="ab\\\\c"; res = StringUtil.unescape(s, null); assertEquals("ab\\c", res); s="ab\\'c"; res = StringUtil.unescape(s, null); assertEquals("ab'c", res); s="ab\\'"; res = StringUtil.unescape(s, null); assertEquals("ab'", res); s="\\\\abc"; res = StringUtil.unescape(s, null); assertEquals("\\abc", res); s="abc\\\\"; res = StringUtil.unescape(s, null); assertEquals("abc\\", res); s="abc\\"; res = StringUtil.unescape(s, null); assertNull(res); s="ab\\xc"; res = StringUtil.unescape(s, null); assertNull(res); s="ab\\xc"; res = StringUtil.unescape(s, "\\'x"); assertEquals("abxc", res); s="abc\\x"; res = StringUtil.unescape(s, "\\'x"); assertEquals("abcx", res); s="ab\\yc"; res = StringUtil.unescape(s, "\\'x"); assertNull(res); s="ab\\\\\\\\c"; res = StringUtil.unescape(s, null); assertEquals("ab\\\\c", res); s="ab\\\\'c"; res = StringUtil.unescape(s, null); assertEquals("ab\\'c", res); s="ab\\'Johnny\\'c"; res = StringUtil.unescape(s, null); assertEquals("ab'Johnny'c", res); s="ab\\\\'Johnny\\\\'c"; res = StringUtil.unescape(s, null); assertEquals("ab\\'Johnny\\'c", res); s="\\\\"; res = StringUtil.unescape(s, null); assertEquals("\\", res); s="\\"; res = StringUtil.unescape(s, null); assertNull(res); s="a"; res = StringUtil.unescape(s, null); assertEquals("a", res); s=""; res = StringUtil.unescape(s, null); assertEquals("", res); res = StringUtil.unescape(null, null); assertNull(res); }