Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java replaceAll not working for \n characters

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

like image 653
user2790289 Avatar asked Sep 18 '13 06:09

user2790289


People also ask

How do you replace a new line character in Java?

Line Break: A line break (“\n”) is a single character that defines the line change. In order to replace all line breaks from strings replace() function can be used.

What does replaceAll \\ s+ do?

\\s+ --> replaces 1 or more spaces. \\\\s+ --> replaces the literal \ followed by s one or more times.

What is the length of \n in Java?

'\n' itself is one character when represented internally in Java, but when interfacing with external systems it can be represented by anywhere between 1 and 8 bytes. Some systems and protocols represent a newline with \r\n , which is 2 characters.


1 Answers

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.

like image 127
Avi Avatar answered Sep 18 '22 16:09

Avi