delmet delmet - 2 years ago 92
Java Question

java new line replacement

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", "");

The output is:

1302248663033 <script language='javascript'>nvieor

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


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("");

Answer Source

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", "");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download