Text cleaning and replacement: delete \n from a text in Java

后端 未结 9 1958
我在风中等你
我在风中等你 2020-12-08 19:57

I\'m cleaning an incoming text in my Java code. The text includes a lot of \"\\n\", but not as in a new line, but literally \"\\n\". I was using replaceAll() from the String

9条回答
  •  温柔的废话
    2020-12-08 20:50

    I think you need to add a couple more slashies...

    String string;
    string = string.replaceAll("\\\\n", "");
    

    Explanation: The number of slashies has to do with the fact that "\n" by itself is a controlled character in Java.

    So to get the real characters of "\n" somewhere we need to use "\n". Which if printed out with give us: "\"

    You're looking to replace all "\n" in your file. But you're not looking to replace the control "\n". So you tried "\n" which will be converted into the characters "\n". Great, but maybe not so much. My guess is that the replaceAll method will actually create a Regular Expression now using the "\n" characters which will be misread as the control character "\n".

    Whew, almost done.

    Using replaceAll("\\n", "") will first convert "\\n" -> "\n" which will be used by the Regular Expression. The "\n" will then be used in the Regular Expression and actually represents your text of "\n". Which is what you're looking to replace.

提交回复
热议问题