将 \n 和 \r\n 替换为
在java中
对于多种语言已经多次询问这个问题,但我无法让它工作。 我有一个像这样的字符串
String str = "This is a string.\nThis is a long string.";
我正在尝试使用
替换 \n
str = str.replaceAll("(\r\n|\n)", "<br />");
但 \n
是没有被替换。 我尝试使用此 RegEx Tool 进行验证,我看到了相同的结果。输入字符串与 "(\r\n|\n)"
不匹配。我做错了什么?
This has been asked several times for several languages but I can't get it to work.
I have a string like this
String str = "This is a string.\nThis is a long string.";
And I'm trying to replace the \n
with <br />
using
str = str.replaceAll("(\r\n|\n)", "<br />");
but the \n
is not getting replaced.
I tried to use this RegEx Tool to verify and I see the same result. The input string does not have a match for "(\r\n|\n)"
. What am i doing wrong ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这对我有用。
结果:
您的问题出在其他地方。
It works for me.
Result:
Your problem is somewhere else.
对我来说,这有效:
提示:使用 正则表达式测试器 进行快速测试,无需编译你的环境
For me, this worked:
Tip: use regex tester for quick testing without compiling in your environment
您正在尝试的更强大的版本:
A little more robust version of what you're attempting:
由于我的帐户是新的,我无法对 Nino van Hooff 的答案进行投票。如果您的字符串来自基于 Windows 的源(例如基于 aspx 的服务器),则此解决方案确实有效:
似乎是一个奇怪的字符集问题,因为双反斜杠被解释为单斜杠转义字符。因此需要上面的四斜杠。
同样,在大多数情况下
"(\\r\\n|\\n)"
应该可以工作,但如果您的字符串来自基于 Windows 的源,请尝试上述操作。只是仅供参考,尝试了一切来纠正我正在替换这些行结尾的问题。起初以为是从
Windows-1252
到UTF-8
的转换失败。但这也不起作用。这个解决方案最终达到了目的。 :)Since my account is new I can't up-vote Nino van Hooff's answer. If your strings are coming from a Windows based source such as an aspx based server, this solution does work:
Seems to be a weird character set issue as the double back-slashes are being interpreted as single slash escape characters. Hence the need for the quadruple slashes above.
Again, under most circumstances
"(\\r\\n|\\n)"
should work, but if your strings are coming from a Windows based source try the above.Just an FYI tried everything to correct the issue I was having replacing those line endings. Thought at first was failed conversion from
Windows-1252
toUTF-8
. But that didn't working either. This solution is what finally did the trick. :)这对我有用。 Java 代码的工作方式与您编写的完全一样。在测试器中,输入字符串应该是:
...带有真正的换行符。您不能使用:
...因为它将
\n
视为文字序列反斜杠'n'。It works for me. The Java code works exactly as you wrote it. In the tester, the input string should be:
...with a real linefeed. You can't use:
...because it treats
\n
as the literal sequence backslash 'n'.这应该可行,但不要为了弄清楚它而自杀。只需使用2次。
免责声明:这不是很有效。
That should work, but don't kill yourself trying to figure it out. Just use 2 passes.
Disclaimer: this is not very efficient.
这应该有效。 输入两个斜杠
您需要在此 参考 中 ,有一个例子显示
我在许多项目中使用了两个斜杠,而且看起来效果很好!
This should work. You need to put in two slashes
In this Reference, there is an example which shows
I have used two slashes in many of my projects and it seems to work fine!