Question

I am working on a school project to build a pseudo terminal and file system. The terminal is scanning System.in and pass the string to controller.

Input to console: abc\r\nabc\r\nabc

Here is the code I tried

Scanner systemIn = Scanner(System.in);
input = systemIn.nextLine();
input = input.replaceAll("\\\\r\\\\n",System.getProperty("line.separator"));
System.out.print(input);

I want java to treat the \r\n I typed to console as a line separator, not actually \ and r. What it does now is print the input as is.

Desired Ouput:

abc

abc

abc

UPDATE: I tried input = StringEscapeUtils.unescapeJava(input); and it solved the problem.

Was it helpful?

Solution

You need to double-escape the regexes in java (once for the regex backslash, once for the Java string). You dont want a linebreak (/\n/, "\\n"), but a backslash (/\\/) plus a "n": /\\n/, "\\\\n". So this should work:

input.replaceAll("(\\\\r)?\\\\n", System.getProperty("line.separator"));

For a more broad handling of escape sequences see How to unescape a Java string literal in Java?

OTHER TIPS

If your input has the string '\r\n', try this

Scanner systemIn = Scanner(System.in);
input = systemIn.nextLine();
input = input.replaceAll("\\\\r\\\\n",System.getProperty("line.separator"))

For consistent behaviour I would replace \\r with \r and \\n with \n rather than replace \\r\\n with the newline as this will have different behaviour on different systems.

You can do

input = systemIn.nextLine().replaceAll("\\\\r", "\r").replaceAll("\\\\n", "\n");

nextLine() strips of the newline at the end. If you want to add a line separator you can do

input = systemIn.nextLine() + System.getProperty("line.separator");

if you are using println() you don't need to add it back.

System.out.println(systemIn.nextLine()); // prints a new line.

As it was mentioned by r0dney, the Bergi's solution doesn't work.

The ability to use some 3rd party libraries is good, however for a person who studies it is better to know the theory, because not for every problem exists some 3rd party library.

Overload project with tons of 3rd party libraries for tasks which can be solved in one line code makes project bulky and not easy maintainable. Anyway here is what's working:

content.replaceAll("(\\\\r)?\\\\n", System.getProperty("line.separator"));

Unless you are actually typing \ and r and \ and n into the console, you don't need to do this at all: instead you have a major misunderstanding. The CR character is represented in a String as \r but it consists of only one byte with the hex value 0xD. And if you are typing backslashes into the console, the simple answer is "don't". Just hit the Enter key: that's what it's for. It will transmit the CR byte into your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top