john
john

Reputation: 707

How to interpret user input of escape character?

User inputs a value such as \n, \t, \r etc

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

\\n, \\t, \\r

Now how do I convert those Strings back into \n, \t, \r

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

What if a user enters some unicode character \u1010 ?

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

How to interpret user input of escape character?

Upvotes: 3

Views: 3377

Answers (1)

Raman Sahasi
Raman Sahasi

Reputation: 31891

You can use unescapeJava method of StringEscapeUtils

unescapeJava

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.in);  

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

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

    }
}

Console

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

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

Upvotes: 3

Related Questions