Search code examples
javajava-5

Java replace special characters in a string


I have a string like this:

BEGIN\n\n\n\nTHIS IS A STRING\n\nEND

And I want to remove all the new line characters and have the result as :

BEGIN THIS IS A STRING END

How do i accomplish this? The standard API functions will not work because of the escape sequence in my experience.


Solution

  • A simple replace('\n', ' ') will cause the string to become:

     BEGIN    THIS IS A STRING  END
          ****                **
    

    where the *'s are spaces. If you want single spaces, try replaceAll("[\r\n]{2,}", " ")

    And in case they're no line breaks but literal "\n"'s wither try:

    replace("\\n", " ")
    

    or:

    replaceAll("(\\\\n){2,}", " ")