Java String Unescape unescape(String str)

Here you can find the source of unescape(String str)

Description

unescape

License

Open Source License

Declaration

public static String unescape(String str) 

Method Source Code

//package com.java2s;
//  are made available under the terms of the Eclipse Public License v1.0

public class Main {
    public static String unescape(String str) {
        if (str == null) {
            // nothing there
            return null;
        }//from   ww w  .j  a v a2  s  .co  m

        int len = str.length();
        if (len <= 1) {
            // impossible to be escaped
            return str;
        }

        StringBuilder ret = new StringBuilder(len - 2);
        boolean escaped = false;
        char c;
        for (int i = 0; i < len; i++) {
            c = str.charAt(i);
            if (escaped) {
                escaped = false;
                switch (c) {
                case 'n':
                    ret.append('\n');
                    break;
                case 'r':
                    ret.append('\r');
                    break;
                case 't':
                    ret.append('\t');
                    break;
                case 'f':
                    ret.append('\f');
                    break;
                case 'b':
                    ret.append('\b');
                    break;
                case '\\':
                    ret.append('\\');
                    break;
                case '/':
                    ret.append('/');
                    break;
                case '"':
                    ret.append('"');
                    break;
                case 'u':
                    ret.append((char) ((dehex((byte) str.charAt(i++)) << 24) + (dehex((byte) str.charAt(i++)) << 16)
                            + (dehex((byte) str.charAt(i++)) << 8) + (dehex((byte) str.charAt(i++)))));
                    break;
                default:
                    ret.append(c);
                }
            } else if (c == '\\') {
                escaped = true;
            } else {
                ret.append(c);
            }
        }
        return ret.toString();
    }

    private static int dehex(byte b) {
        if ((b >= '0') && (b <= '9')) {
            return (byte) (b - '0');
        }
        if ((b >= 'a') && (b <= 'f')) {
            return (byte) ((b - 'a') + 10);
        }
        if ((b >= 'A') && (b <= 'F')) {
            return (byte) ((b - 'A') + 10);
        }
        throw new IllegalArgumentException("!hex:" + Integer.toHexString(0xff & b));
    }
}

Related

  1. unescape(String src)
  2. unescape(String src)
  3. unescape(String src)
  4. unescape(String st)
  5. unescape(String str)
  6. unescape(String str)
  7. unescape(String str)
  8. unescape(String str)
  9. unescape(String str)