// begin of ConvertEscapedChars.java
public class ConvertEscapedChars {
public static void main(String[] args) {
final String orig = "This is a return:\\r\\nThis is "
+ "a tab:\\tand this is a backslash:\\\\.\r\n"
+ "Others are the backspace \\b\r\nthe formfeed \\f\r\n"
+ "single quote \\'\r\ndouble quote \\\"\r\n"
+ "one character octal \\7\r\ntwo character octal \\76\r\n"
+ "three character octal \\176\r\n"
+ "two character octal escape followed by octal digit \\767\r\n"
+ "\t(note that this is not a 3-char octal escape because "
+ "first digit is bigger than 3)\r\n"
+ "two character octal escape followed by non-octal digit "
+ "\\768\r\n"
+ "one character octal escape followed by non-octal digit "
+ "\\78\r\n"
+ "an invalid escape sequence \\w\r\n"
+ "an unterminated escape sequence \\";
System.out.println("------- Original -------");
System.out.println(orig);
System.out.println("------------------------");
System.out.println();
final String conv = convertEscapedChars(orig);
System.out.println("------- Converted ------");
System.out.println(conv);
System.out.println("------------------------");
}
/**
* Replaces escape sequences in the given String <code>s</code> by
* the actual characters they represent. The escape sequences that
* are recognized are those that are defined in section 3.10.6 of
* the JLS, 3rd ed. Invalid escape sequences are left untouched.
*
* @param s
* the String to convert
* @return a String where escape sequences have been replaced by
* their actual character
* @see
http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#101089
*/
public static String convertEscapedChars(String s) {
int n = s == null ? 0 : s.length();
if (n == 0) {
return s; // null or empty string
}
StringBuffer result = new StringBuffer(n);
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c != '\\') {
result.append(c);
} else {
if (++i < n) {
c = s.charAt(i);
switch (c) {
case 'b':
result.append('\b');
break;
case 't':
result.append('\t');
break;
case 'n':
result.append('\n');
break;
case 'f':
result.append('\f');
break;
case 'r':
result.append('\r');
break;
case '\"':
result.append('\"');
break;
case '\'':
result.append('\'');
break;
case '\\':
result.append('\\');
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
// OctalEscape
StringBuffer octal =
new StringBuffer(3).append(c);
if (i + 1 < n && (c = s.charAt(i + 1)) >= '0'
&& c <= '7') {
i++;
octal.append(c);
if (i + 1 < n && (c = s.charAt(i + 1))>= '0'
&& c <= '7') {
i++;
octal.append(c);
}
}
if (octal.length()==3 && octal.charAt(0)>'3') {
i--;
octal.setLength(2);
}
result.append(
(char) Integer.parseInt(octal.toString(),
8));
break;
default:
System.err.println(
"Invalid escape sequence: \\" + c);
result.append('\\').append(c);
break;
}
} else {
System.err.println("Unterminated escape sequence");
result.append('\\');
}
}
}
return result.toString();
}
}
// end of ConvertEscapedChars.java