java replaceAll not working for \n characters

前端 未结 4 615
执念已碎
执念已碎 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: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.

提交回复
热议问题