java replaceAll not working for \n characters

17,468

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");
Share:
17,468

Related videos on Youtube

user2790289
Author by

user2790289

Updated on June 01, 2020

Comments

  • user2790289
    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 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

    • gifpif
      gifpif almost 11 years
      i think use replaceAll("\\\\n","\\n");
  • SpringLearner
    SpringLearner almost 11 years
    when i tried this way its working,String x="x\ny"; String y=x.replaceAll("\\n", "\n"); System.out.println(y);
  • nhahtdh
    nhahtdh almost 11 years
    @javaBeginner: Your original string contains the new line already.
  • SpringLearner
    SpringLearner almost 11 years
    isnt this same way that of OP?
  • nhahtdh
    nhahtdh almost 11 years
    @javaBeginner: No. OP's raw string contains a \ followed by n, which means in Java literal, it would be "something\\nsomething"
  • SpringLearner
    SpringLearner almost 11 years
    I am confused,still +1 for this answer
  • nhahtdh
    nhahtdh almost 11 years
    @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.

Related