How to change "\\r\\n" to line separator in java

r0dney picture r0dney · Jul 18, 2012 · Viewed 13.6k times · Source

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.

Answer

Bergi picture Bergi · Jul 18, 2012

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?