java换行 [英] java new line replacement

查看:108
本文介绍了java换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么我没有得到预期的结果:

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

输出为:

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

所以我想知道为什么\n仍然存在.有人知道吗? \ n在某种程度上特别吗?

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

因此我在将换行符与匹配时遇到了麻烦.在正则表达式中,没有意识到使用DOTALL选项的用途,因此我将在此处添加需要做的事情以供将来参考:

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

推荐答案

字符串是不可变的.像replaceAll这样的字符串操作不会修改您调用它的实例,它们会返回新的String实例.解决方案是将修改后的字符串分配给您的原始变量.

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

这篇关于java换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆