简体   繁体   中英

Unable to replace \\n with empty string using java

Trying to replace \\n from a String with "",
after removing the \\n the expected o/p  would be:  "This is not working ";
Tried samples : 

 String str = "This \\nis \\n\\nnot \\n\\nworking ";

   str.replaceAll("\\n","");
  • This is not working.
    Could you please Help me out how to fix this issue?

You'll have to use \\\\n instead of a \\n . This should work:

String str = "This \\nis \\n\\nnot \\n\\nworking ";
System.out.println(str.replaceAll("\\\\n",""));

You can refer to online regex generator to explore more patterns. This would really help!

Meanwhile I guess below example should serve your use case:

public class RegularExpression {

public static void main(String[] args) {
    
    String originalString = "This \\nis \\n\\nnot \\n\\nworking ";

    String newString = originalString.replaceAll("\\\\n","");

    System.out.println(newString);

}

}

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