-2

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);
Mark Rotteveel
110k241 gold badges160 silver badges233 bronze badges
asked Feb 6, 2023 at 11:58
5
  • \r\n is not the only possible variant. It could be just one \n char in there. But also - if you aren't getting the correct output - what DO you get? Commented Feb 6, 2023 at 12:02
  • @M.Prokhorov, I tried, but I'm not getting the correct output. Commented Feb 6, 2023 at 12:08
  • In the regex, you should use \r\n, not \\r\\n (though \\r\\n should work as well). Please show the actual codepoints of the string. Commented Feb 6, 2023 at 12:18
  • in = in.replaceAll("[\r\n]",""); Commented Feb 6, 2023 at 12:24
  • OK will add as answer for you to accept Commented Feb 6, 2023 at 13:17

2 Answers 2

1

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

answered Feb 6, 2023 at 12:21
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for answering. I am currently using Java 7, so I tagged it as Java 7. I tried the code below (in = in.replaceAll("[\r\n]","");) and it is working fine.
0

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","");
answered Feb 6, 2023 at 13:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.