I do not think the following will work in the intended way with String#replaceAll
:
myText.replaceAll("\\r\\n", "\n")
The reason is, String#replaceAll
expects a regex and in order to escape \
, you need another \
but since it's a regex pattern, you need another pair of \\
(the way you do it e.g. in \\s
).
It should be
myText.replaceAll("(\\\\r\\\\n)", "\n");
which means \r\n
will be replaced with \n
.
Alternatively, you can use String#replace which expects the string to be replaced instead of regex as is the case with String#replaceAll i.e. myText.replace("\\r\\n", "\n")
will work in the same way as myText.replaceAll("(\\\\r\\\\n)", "\n")
does.
public class Main {
public static void main(String[] args) {
String myText = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\\r\\n\n" + "\n"
+ "Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus\\r\\n\n" + "\n"
+ "et magnis dis parturient montes, nascetur ridiculus mus.\\r\\n \n" + "\n" + "Don12345";
System.out.println(myText);
System.out.println("---------------------------------------------------------------------------");
String result = myText.replaceAll("(\\\\r\\\\n)", "\n");
System.out.println(result);
}
}
Output:
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\r\n
Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus\r\n
et magnis dis parturient montes, nascetur ridiculus mus.\r\n
Don12345
---------------------------------------------------------------------------
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus
et magnis dis parturient montes, nascetur ridiculus mus.
Don12345