java new line replacement
Asked Answered
S

3

7

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);
Soutache answered 14/4, 2011 at 3:13 Comment(0)
T
21

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", "");
Topdress answered 14/4, 2011 at 3:16 Comment(1)
To be portable between OSes, use System.getProperty("line.separator") in lieu of linefeed character.Haywoodhayyim
S
1

Yes, \n is special. It is an escape sequence that stands for a newline. You need to escape it in a string literal in order for it to be actually interpreted the way you want. Append a \ before the sequence so that it looks like this:

"\\n"

Now your program should look like this:

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

Of course if the string t is coming from somewhere rather than actually being typed by you into the program then you need only add the extra slash in your call to replaceAll()

Edited according to comments.

Strophanthin answered 14/4, 2011 at 3:20 Comment(1)
I missed the other error everyone else has pointed out. You do need to take the result of the replaceAll() call and use that, not the original string.Strophanthin
B
0
public static String escape(String s) {
    return s
            .replaceAll("\n", "")
            .replaceAll("\r", "");
}
Baldheaded answered 24/8, 2021 at 3:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.