Java Java String Unescape unescapeJava(final String s)

Here you can find the source of unescapeJava(final String s)

Description

unescape java strings well enough for our purposes.

License

Open Source License

Declaration

public static String unescapeJava(final String s) 

Method Source Code

//package com.java2s;
/**//from  w w w  .j av  a  2 s .  c  o  m
 * ADOBE SYSTEMS INCORPORATED
 * Copyright 2009-2013 Adobe Systems Incorporated
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute
 * this file in accordance with the terms of the MIT license,
 * a copy of which can be found in the LICENSE.txt file or at
 * http://opensource.org/licenses/MIT.
 */

public class Main {
    /**
     * unescape java strings well enough for our purposes.
     * Note: rather than throwing, we pass invalid
     * unicode sequences escaped through to the result.
     */
    public static String unescapeJava(final String s) {
        final StringBuilder b = new StringBuilder();
        final int n = s.length();

        for (int i = 0; i < n;) {
            final char c = s.charAt(i++);

            if (c == '\\' && i < n) {
                final char e = s.charAt(i++);

                switch (e) {
                case 'u': {
                    if (i < n - 3) {
                        try {
                            b.append((char) Integer.parseInt(
                                    "" + s.charAt(i++) + s.charAt(i++) + s.charAt(i++) + s.charAt(i++), 16));

                            continue;
                        } catch (NumberFormatException nfe) {
                            i -= 4;
                        }
                    }

                    b.append("\\u");
                    break;
                }
                case '\\':
                    b.append('\\');
                    break;
                case '\'':
                    b.append('\'');
                    break;
                case '\"':
                    b.append('"');
                    break;
                case 'r':
                    b.append('\r');
                    break;
                case 'f':
                    b.append('\f');
                    break;
                case 't':
                    b.append('\t');
                    break;
                case 'n':
                    b.append('\n');
                    break;
                case 'b':
                    b.append('\b');
                    break;
                default:
                    b.append(c).append(e);
                    break;
                }
            } else {
                b.append(c);
            }
        }

        return b.toString();
    }
}

Related

  1. unescapeJava(final String str)
  2. unescapeJava(final String str)
  3. unescapeJava(String escaped)
  4. unescapeJava(String s)