0

I am using the wikimedia api to get content from wikipedia pages. The api returns a lot of "\n" as plain text. I want to remove them from a string

s = s.replaceAll("\\n", "");
s = s.replaceAll("\n", "");

Neither of these work, any ideas?

yxting
  • 51
  • 1
  • 5
  • 1
    Give us an example of the source text – Blagoj Atanasovski Oct 16 '18 at 14:00
  • 1
    Possible duplicate of [How to remove line breaks from a file in Java?](https://stackoverflow.com/questions/2163045/how-to-remove-line-breaks-from-a-file-in-java) – Chris Prolls Oct 16 '18 at 14:00
  • https://stackoverflow.com/questions/2163045/how-to-remove-line-breaks-from-a-file-in-java – pedroke Oct 16 '18 at 14:01
  • Possible duplicate of [Remove end of line characters from Java string](https://stackoverflow.com/questions/593671/remove-end-of-line-characters-from-java-string) – LuCio Oct 16 '18 at 14:23

3 Answers3

2

When your String contains a plaintext \n it is actually a \\n otherwise it would be displayed as a linebreak, which is why I found s = s.replaceAll("\\\\n","") to be working for me. An example snippet:

class Main{
  public static void main(String[] args){
        String s = "Hello\\nHello";
        System.out.println(s);
        s = s.replaceAll("\\\\n","");
        System.out.println(s);
    }
}

Remember that replaceAll takes a Regex: Since you want to replace 2 /s you have to escape both of them, therefore////

tistorm
  • 381
  • 1
  • 8
0

Hi Please to use below code format:

s= s.replace("\n", "").replace("\r", "");

Thanks

GauravRai1512
  • 834
  • 6
  • 14
0

You can use the code below:

s = s.replace("\n", "");

but, the newline character can be different among the environments. So, you can use this

s = s.replace(System.getProperty("line.separator"), "");