java replaceAll not working for \n characters
Asked Answered
A

4

15

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

Astrophotography answered 18/9, 2013 at 6:36 Comment(1)
i think use replaceAll("\\\\n","\\n");Fortify
P
31

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.

Pahari answered 18/9, 2013 at 6:38 Comment(0)
G
4

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
Gerstner answered 18/9, 2013 at 6:39 Comment(6)
when i tried this way its working,String x="x\ny"; String y=x.replaceAll("\\n", "\n"); System.out.println(y);Pollerd
@javaBeginner: Your original string contains the new line already.Gerstner
isnt this same way that of OP?Pollerd
@javaBeginner: No. OP's raw string contains a \ followed by n, which means in Java literal, it would be "something\\nsomething"Gerstner
I am confused,still +1 for this answerPollerd
@javaBeginner: OP's string contains \ followed by an n. 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.Gerstner
C
3

You need to escape \ character. So try

replaceAll("\\\\n", "\n");
Chrisman answered 18/9, 2013 at 6:39 Comment(0)
S
3

replaceAll is using Regular Expressions, you can use replace which will also replace all '\n':

replace("\\\\n", "\n");
Shutz answered 18/9, 2013 at 6:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.