Basically, all I'm trying to do is remove the newline character from a String in Java. I've looked at dozens of posts asking similar questions and they all say the same thing, but none of them seem to work for me. Here is all the code I have 3 lines:
String text = "\\n texttexttext \\n";
text = text.replaceAll("\\n", "");
System.out.println(text);
That string is similar to what I'm actually trying to use, but even with this one I can't find the newline character and replace it. The replaceAll just won't see it and I don't know why.
I've tried plenty of other things too like
text = text.replaceAll("\\n", "").replaceAll("\\r", "");
or
text = text.replaceAll("\\r\\n|\\r|\\n", " ");
but nothing can even find the character. I haven't even been able to find it using Regex Pattern and Matcher objects. The only thing slightly unusual I'm doing is doing it in a Junit Test bean, but I cannot believe that would do anything.
Line Break: A line break (“\n”) is a single character that defines the line change. In order to replace all line breaks from strings replace() function can be used.
The canonical way to strip end-of-line (EOL) characters is to use the string rstrip() method removing any trailing \r or \n.
It is a character in a string which represents a line break, which means that after this character, a new line will start. There are two basic new line characters: LF (character : \n, Unicode : U+000A, ASCII : 10, hex : 0x0a): This is simply the '\n' character which we all know from our early programming days.
You don't have a newline character in your original text
. You have escaped the backslash, not the n
, so you have actual backslash \
and n
characters in your text
string.
You did have to escape the backslash character in your regular expression, but not in your literal string text.
If you initialize text
as "\n texttexttext \n"
, then it will find and replace those newlines as expected.
String newLine = System.getProperty("line.separator")
System.out.println(newLine.contains("\n")); // this is a new line
System.out.println(newLine.contains("\\n"));
output:
true
false
As commented by Jon Lin
Your example text does not actually talk about newlines - \\n
is the string \n
.
The other fallacy is that replaceAll
expects a regular expression as the first input. So \\n
is actually replaced to \n
as \
is the escaping character, which is then interpreted as a newline character - case of double escaping, thus in your input text \\
is not matched.
If you try
text = text.replaceAll("\\\\n", "");
At least you get the expected result, as it's both a Java string and a regular expression both interpret \
as escaping character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With