Java String Unescape unescapeString(String text)

Here you can find the source of unescapeString(String text)

Description

Effectively un-escapes a string, performs the reverse of #escapeString(String) .

License

Open Source License

Parameter

Parameter Description
text - the String to un-escape

Return

the un-escaped

Declaration

public static String unescapeString(String text) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from  ww w . ja v  a  2s. co  m*/
     * <p>List of characters that need un-escaping.</p>
     */
    private static final String[] NEED_UNESCAPING = new String[] { "\\r",
            "\\n", "\\N", "\\\\", "\\,", "\\;", "\\:" };

    /**
     * <p>Effectively un-escapes a string, performs the reverse of {@link #escapeString(String)}.
     * The characters the get unescaped are as follows:
     * <ul>
     *    <li>\\n -> \n</li>
     *    <li>\\r -> r</li>
     *    <li>\\N ->\N</li>
     *    <li>\\; -> \</li>
     *    <li>\, -> ,</li>
     *    <li>\; -> ;</li>
     *    <li>\: -> :</li>
     * </ul>
     * </p>
     *
     * @param text - the {@link String} to un-escape
     * @return the un-escaped {@link String}
     */
    public static String unescapeString(String text) {
        if (!needsUnEscaping(text)) {
            return text;
        }

        String unescaped = text.replaceAll("\\\\n", "\n");
        unescaped = unescaped.replaceAll("\\\\r", "\r");
        unescaped = unescaped.replaceAll("\\\\N", "\n");
        unescaped = unescaped.replaceAll("\\\\\\\\", "\\\\");
        unescaped = unescaped.replaceAll("\\\\,", ",");
        unescaped = unescaped.replaceAll("\\\\;", ";");
        unescaped = unescaped.replaceAll("\\\\:", ":");
        return unescaped;
    }

    /**
     * <p>Returns true if the specified textual string contains any
     * one of the following characters defined in the constant String[]
     * of {@link #NEED_UNESCAPING}.</p>
     *
     * @param text - the {@link String} to check
     * @return true if the given {@link String} requires un-escaping or false otherwise
     */
    public static boolean needsUnEscaping(String text) {
        boolean needs = false;
        for (int i = 0; i < NEED_UNESCAPING.length; i++) {
            if (text.indexOf(NEED_UNESCAPING[i]) != -1) {
                needs = true;
                break;
            }
        }

        return needs;
    }
}

Related

  1. unescapeString(String str)
  2. unEscapeString(String str)
  3. unescapeString(String string)
  4. unescapeString(String string, String escapeChars, char escapeSymbol)
  5. unescapeString(String t)
  6. unescapeString(String text)
  7. unescapeString(String text)
  8. unescapeString(String txt)
  9. unescapeText(String s)