java replaceAll not working for \n characters

早过忘川 提交于 2020-02-20 07:03:31

问题


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

Barber

this is my code for this

replaceAll("\\n", "\n");

but it is not working and giving me same string John \n Barber


回答1:


You need to do:

replaceAll("\\\\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.




回答2:


You need to escape \ character. So try

replaceAll("\\\\n", "\n");



回答3:


replaceAll is using Regular Expressions, you can use replace which will also replace all '\n':

replace("\\\\n", "\n");



回答4:


Since \n (or even the raw new line character U+000A) in regex is interpreted as new line character, you need \\n (escape the \) to specify slash \ followed by n.

That is from the regex engine's perspective.

From the compiler's perspective, in Java literal string, you need to escape \, so we add another layer of escaping:

String output = inputString.replaceAll("\\\\n", "\n");
//                                      \\n      U+000A


来源:https://stackoverflow.com/questions/18865393/java-replaceall-not-working-for-n-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!