java replaceAll not working for \n characters

user2790289 picture user2790289 · Sep 18, 2013 · Viewed 16.2k times · Source

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

this is my code for this

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

but it is not working and giving me same string John \n Barber

Answer

Avi picture Avi · Sep 18, 2013

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.