java replaceAll not working for \n characters
Solution 1
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.
Solution 2
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
Solution 3
You need to escape \
character. So try
replaceAll("\\\\n", "\n");
Solution 4
replaceAll is using Regular Expressions, you can use replace which will also replace all '\n':
replace("\\\\n", "\n");
Related videos on Youtube
user2790289
Updated on June 01, 2020Comments
-
user2790289 about 4 years
I have a string like this:
John \n Barber
now I want to replace \n with actual new line character so it will becomeJohn
Barber
this is my code for this
replaceAll("\\n", "\n");
but it is not working and giving me same string
John \n Barber
-
gifpif almost 11 yearsi think use replaceAll("\\\\n","\\n");
-
-
SpringLearner almost 11 yearswhen i tried this way its working,String x="x\ny"; String y=x.replaceAll("\\n", "\n"); System.out.println(y);
-
nhahtdh almost 11 years@javaBeginner: Your original string contains the new line already.
-
SpringLearner almost 11 yearsisnt this same way that of OP?
-
nhahtdh almost 11 years@javaBeginner: No. OP's raw string contains a
\
followed byn
, which means in Java literal, it would be"something\\nsomething"
-
SpringLearner almost 11 yearsI am confused,still +1 for this answer
-
nhahtdh almost 11 years@javaBeginner: OP's string contains
\
followed by ann
. That is the difference here. If you want to make it clear, try to write a program that take input from command prompt, and use the replaceAll on it.