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

后端 未结 9 1966
我在风中等你
我在风中等你 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:39

    Hooknc is right. I'd just like to post a little explanation:

    "\\n" translates to "\n" after the compiler is done (since you escape the backslash). So the regex engine sees "\n" and thinks new line, and would remove those (and not the literal "\n" you have).

    "\n" translates to a real new line by the compiler. So the new line character is send to the regex engine.

    "\\\\n" is ugly, but right. The compiler removes the escape sequences, so the regex engine sees "\\n". The regex engine sees the two backslashes and knows that the first one escapes it so that translates to checking for the literal characters '\' and 'n', giving you the desired result.

    Java is nice (it's the language I work in) but having to think to basically double-escape regexes can be a real challenge. For extra fun, it seems StackOverflow likes to try to translate backslashes too.

提交回复
热议问题