john john - 1 year ago 76
Java Question

How to interpret user input of escape character?

User inputs a value such as


Java of course escapes the above characters with a backslash. So the application has the following Strings in the buffer


Now how do I convert those Strings back into

I could write an
statement. But there is unlimited number of options

What if a user enters some unicode character

This doesn't work
userInput.replaceAll("\\\\", "\\")

How to interpret user input of escape character?

Answer Source

You can use unescapeJava method of StringEscapeUtils


public static String unescapeJava(String str)
Unescapes any Java literals found in the String. For example, it will turn a sequence of '\' and 'n' into a newline character, unless the '\' is preceded by another '\'.

Parameters: str - the String to unescape, may be null
Returns: a new unescaped String, null if null string input

However, if you don't want to convert these escaped characters into their actual meaning, (like \n to new line), then there's really no need for you to unescape the characters. Java only escapes those characters to store them in variables. If you're planning to output it to user, then java will automatically unescape it.

Consider this code,

import java.util.Scanner;  

public class Adding {
    public static void main(String[] args) {
        Scanner sc=new Scanner(;  

        System.out.print("Please enter something : ");
        String userInput = sc.nextLine();

        System.out.println("You Entered : " + userInput);



Please enter something : hello\nworld
You Entered : hello\nworld

In the above example, hello\nworld was stored as hello\\nworld in variable userInput.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download