Remove end of line characters from Java string

Viewed 202437

I have string like this

"hello
java
book"

I want remove \r and \n from String(hello\r\njava\r\nbook). I want the result to be "hellojavabook". How can I do this?

12 Answers

Regex with replaceAll.

public class Main
{
    public static void main(final String[] argv) 
    {
        String str;

        str = "hello\r\njava\r\nbook";
        str = str.replaceAll("(\\r|\\n)", "");
        System.out.println(str);
    }
}

If you only want to remove \r\n when they are pairs (the above code removes either \r or \n) do this instead:

str = str.replaceAll("\\r\\n", "");

If you want to avoid the regex, or must target an earlier JVM, String.replace() will do:

str=str.replace("\r","").replace("\n","");

And to remove a CRLF pair:

str=str.replace("\r\n","");

The latter is more efficient than building a regex to do the same thing. But I think the former will be faster as a regex since the string is only parsed once.

public static void main(final String[] argv) 
{
    String str;

    str = "hello\r\n\tjava\r\nbook";
    str = str.replaceAll("(\\r|\\n|\\t)", "");
    System.out.println(str);
}

It would be useful to add the tabulation in regex too.

Given a String str:

str = str.replaceAll("\\\\r","")
str = str.replaceAll("\\\\n","")

You can either directly pass line terminator e.g. \n, if you know the line terminator in Windows, Mac or UNIX. Alternatively you can use following code to replace line breaks in either of three major operating system.

str = str.replaceAll("\\r\\n|\\r|\\n", " ");

Above code line will replace line breaks with space in Mac, Windows and Linux. Also you can use line-separator. It will work for all OS. Below is the code snippet for line-separator.

String lineSeparator=System.lineSeparator();
String newString=yourString.replace(lineSeparator, "");

Have you tried using the replaceAll method to replace any occurence of \n or \r with the empty String?

You can use unescapeJava from org.apache.commons.text.StringEscapeUtils like below

str = "hello\r\njava\r\nbook";
StringEscapeUtils.unescapeJava(str);

Hey we can also use this regex solution.

String chomp = StringUtils.normalizeSpace(sentence.replaceAll("[\\r\\n]"," "));

I went with \\s+ and it removed \r and \n chars for me.

\s+ will match one or more whitespace characters

final String stringWithWhitespaceChars = "Bart\n\r";
final String stringWithoutEscapeChars = stringWithEscapeChars.replaceAll("\\s+","");

Refer to Regex expressions in Java, \\s vs. \\s+ for in detail informations.

Try below code. It worked for me.

str = str.replaceAll("\\r", "");
str = str.replaceAll("\\n", "");
Related