Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing \n in a String

There are several answers to similar questions as mine, but I have tried several of them and they are not working. I must be doing something stupid.

I have

String newline = System.getProperty("line.separator");
String content = "Test\n another line\n";
if(content.contains("\\n")) {
    content = content.replaceAll("(\\n)", newline);
    System.out.print(content);
}

I also tried "\n" and "\\n" in the regex. The content remains unchanged using replaceAll.

like image 949
hclDave Avatar asked Jul 10 '26 06:07

hclDave


1 Answers

Okay facts:

  • \r is a CR, U+000D
  • \n is a LF, U+000A

Those characters you can put in a String

String s = "line 1.\nline 2.\n";
String newline = System.getProperty("line.separator");

newline can be "\n" (1 char) or "\r\n" (2 chars) or still something else.

If you would read this text, reading first a backslash and then an n, it would be in code:

String nl = "\\n"; // Two chars, an escaped backslash and a `n`.
String nl = "\\" + 'n'; // Two chars, an escaped backslash and a `n`.

If you would want to replace these two chars with a real newline:

s = s.replace("\\n", "\n");
s = s.replace("\\n", newline); // Platform dependent

Now java regex is still more complex, as it escapes regex letters with a backslash, which in Strings is escaped itself:

You will not need a regex replaceAll/replaceFirst here, but it would go as:

s = s.replaceAll("\\\\n", "\n");

The pattern containing two backslashes: regex escaping of one backslash.

like image 181
Joop Eggen Avatar answered Jul 13 '26 17:07

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!