java java换行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5658134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java new line replacement
提问by delmet
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?
所以我想知道为什么\n
仍然存在。有人知道吗?\n 有什么特别之处吗?
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:
所以我在将换行符与 . 在正则表达式中,没有意识到使用 DOTALL 选项,所以我将在这里添加一个需要做的事情以供将来参考:
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);
回答by Jonathon Faust
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.
字符串是不可变的。字符串操作,例如replaceAll
不修改您调用它的实例,它们返回新的 String 实例。解决方案是将修改后的字符串分配给您的原始变量。
t = t.replaceAll("\n", "");
回答by chandsie
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
很特别。这是一个代表换行符的转义序列。您需要在字符串文字中对其进行转义,以便按照您想要的方式实际解释它。在序列前附加一个 \ 使其看起来像这样:
"\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()
当然,如果字符串t
来自某个地方而不是您实际输入到程序中,那么您只需要在调用中添加额外的斜线replaceAll()
Edited according to comments.
根据评论编辑。