简体   繁体   中英

Remove plaintext \n from string in Java

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?

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 ////

Hi Please to use below code format:

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

Thanks

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"), "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM