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
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.
\\s+ --> replaces 1 or more spaces. \\\\s+ --> replaces the literal \ followed by s one or more times.
'\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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With