java replaceAll not working for \n characters

前端 未结 4 609
执念已碎
执念已碎 2021-01-04 08:01

I have a string like this: John \\n Barber now I want to replace \\n with actual new line character so it will become

John

Barber<

相关标签:
4条回答
  • 2021-01-04 08:31

    replaceAll is using Regular Expressions, you can use replace which will also replace all '\n':

    replace("\\\\n", "\n");
    
    0 讨论(0)
  • 2021-01-04 08:32

    You need to do:

    replaceAll("\\\\n", "\n");
    

    The replaceAll method expects a regex in its first argument. When passing 2 \ in java string you actually pass one. The problem is that \ is an escape char also in regex so the regex for \n is actualy \\n so you need to put an extra \ twice.

    0 讨论(0)
  • 2021-01-04 08:52

    You need to escape \ character. So try

    replaceAll("\\\\n", "\n");
    
    0 讨论(0)
  • 2021-01-04 08:52

    Since \n (or even the raw new line character U+000A) in regex is interpreted as new line character, you need \\n (escape the \) to specify slash \ followed by n.

    That is from the regex engine's perspective.

    From the compiler's perspective, in Java literal string, you need to escape \, so we add another layer of escaping:

    String output = inputString.replaceAll("\\\\n", "\n");
    //                                      \\n      U+000A
    
    0 讨论(0)
提交回复
热议问题