java new line replacement

delmet picture delmet · Apr 14, 2011 · Viewed 16.7k times · Source

I am wondering about why I don't get the expected result with this one:

String t = "1302248663033   <script language='javascript'>nvieor\ngnroeignrieogi</script>";
t.replaceAll("\n", "");
System.out.println(t);

The output is:

1302248663033   <script language='javascript'>nvieor
gnroeignrieogi</script>

So I am wondering why \n is still there. Anybody knows? Is \n special in someway?

EDIT:

So I was having trouble with matching the newline character with a . in a regex expression, not realizing that one use to use the DOTALL option, so I'll add what one needs to do here for future reference:

String text = null;
text = FileUtils.readFileToString(inFile);
Pattern p = Pattern.compile("<script language='javascript'>.+?</script>\n", Pattern.DOTALL);
text = p.matcher(text).replaceAll("");
out.write(text);

Answer

Jonathon Faust picture Jonathon Faust · Apr 14, 2011

Strings are immutable. String operations like replaceAll don't modify the instance you call it with, they return new String instances. The solution is to assign the modified string to your original variable.

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