What is the best way to remove a hard enter from a String?
Input:
String in= "strengthened columns
with GRPES
";
Expected output: strengthened columns with GRPES
I tried the below code, but it's not working for me.
in = in.replaceAll("\\r\\n","");
System.out.println(in);
2 Answers 2
Unless you don't have a specific reason to use java-7 today, Here's a solution using java 13 or above
String in= """
strengthened columns
with GRPES
""";
in = in.replaceAll("\\n","");
System.out.println(in);
I have observed the question is tagged with java-7, do let me know if you are looking for a solution specific to the version
1 Comment
in = in.replaceAll("[\r\n]","");) and it is working fine.Actually you don't escape standard escape sequences when you use regexes. Also you don't want to specify an order of escape sequences - you just want to eliminate any type of line separator, so
in = in.replaceAll("[\r\n]","");
With later versions of Java, that could probably be
in = in.replaceAll("\\R","");
\r\nis not the only possible variant. It could be just one\nchar in there. But also - if you aren't getting the correct output - what DO you get?\r\n, not\\r\\n(though\\r\\nshould work as well). Please show the actual codepoints of the string.in = in.replaceAll("[\r\n]","");