Java replaceAll不适用于\ n字符 [英] java replaceAll not working for \n characters
本文介绍了Java replaceAll不适用于\ n字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的字符串: John \ n Barber
现在我想用实际的换行符替换\ n,这样它将变成
I have a string like this: John \n Barber
now I want to replace \n with actual new line character so it will become
John
理发师
这是我的代码
replaceAll("\\n", "\n");
但是它不能正常工作,并且给我相同的字符串 John \ n Barber
but it is not working and giving me same string John \n Barber
推荐答案
您需要这样做:
replaceAll("\\\\n", "\n");
replaceAll
方法在其第一个参数中需要一个正则表达式.当在Java字符串中传递2 \
时,您实际上传递了一个.问题在于 \
也是正则表达式中的转义字符,因此 \ n
的正则表达式实际上是 \\ n
,因此您需要放置一个额外的 \
两次.
The replaceAll
method expects a regex in its first argument. When passing 2 \
in java string you actually pass one. The problem is that \
is an escape char also in regex so the regex for \n
is actualy \\n
so you need to put an extra \
twice.
这篇关于Java replaceAll不适用于\ n字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文