Java String Unescape unescape(String src)

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

Description

Un-escapes the passed string, replacing the standard slash escapes with their corresponding unicode character value.

License

Apache License

Declaration

public static String unescape(String src) 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

public class Main {
    /**/* w  w w.  j  a  v  a  2 s .co m*/
     *  Un-escapes the passed string, replacing the standard slash escapes
     *  with their corresponding unicode character value.
     */
    public static String unescape(String src) {
        if (src == null)
            return null;

        StringBuilder sb = new StringBuilder(src);
        for (int ii = 0; ii < sb.length(); ii++) {
            if (sb.charAt(ii) == '\\') {
                sb.deleteCharAt(ii);
                if ((sb.charAt(ii) == 'u') || (sb.charAt(ii) == 'U')) {
                    int c = (hex2dec(sb.charAt(ii + 1)) << 12) + (hex2dec(sb.charAt(ii + 2)) << 8)
                            + (hex2dec(sb.charAt(ii + 3)) << 4) + hex2dec(sb.charAt(ii + 4));
                    sb.setCharAt(ii, (char) c);
                    sb.delete(ii + 1, ii + 5);
                } else if (sb.charAt(ii) == 'b')
                    sb.setCharAt(ii, '\b');
                else if (sb.charAt(ii) == 't')
                    sb.setCharAt(ii, '\t');
                else if (sb.charAt(ii) == 'n')
                    sb.setCharAt(ii, '\n');
                else if (sb.charAt(ii) == 'f')
                    sb.setCharAt(ii, '\f');
                else if (sb.charAt(ii) == 'r')
                    sb.setCharAt(ii, '\r');
                // FIXME - handle octal escape
            }
        }
        return sb.toString();
    }

    /**
     *  Returns the length of the passed string, 0 if the string is null.
     *
     *  @since 1.0.12
     */
    public static int length(String str) {
        return (str == null) ? 0 : str.length();
    }

    /**
     *  Returns the numeric value of a hex digit.
     */
    private static int hex2dec(char c) {
        if ((c >= '0') && (c <= '9'))
            return (c - '0');
        else if ((c >= 'A') && (c <= 'F'))
            return (c - 'A') + 10;
        else if ((c >= 'a') && (c <= 'f'))
            return (c - 'a') + 10;

        throw new IllegalArgumentException("not a hex digit: " + c);
    }
}

Related

  1. unescape(String s)
  2. unescape(String s, char[] charsToEscape)
  3. unescape(String s, int i)
  4. unescape(String s, String toUnescape)
  5. unescape(String source)
  6. unescape(String src)
  7. unescape(String src)
  8. unescape(String src)
  9. unescape(String st)