java replaceAll 不适用于 \n 个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18865393/
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 replaceAll not working for \n characters
提问by user2790289
I have a string like this: John \n Barbernow I want to replace \n with actual new line character so it will become
我有一个这样的字符串:John \n Barber现在我想用实际的换行符替换 \n 所以它会变成
John
John
Barber
理发师
this is my code for this
这是我的代码
replaceAll("\n", "\n");
but it is not working and giving me same string John \n Barber
但它不起作用并给我相同的字符串 John \n Barber
采纳答案by Avi
You need to do:
你需要做:
replaceAll("\\n", "\n");
The replaceAllmethod 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 \nis actualy \\nso you need to put an extra \twice.
该replaceAll方法需要在其第一个参数中使用正则表达式。\在 java 字符串中传递 2 时,您实际上传递了一个。问题是,\是一种逃避字符也正则表达式,因此正则表达式\n是actualy \\n,所以你需要把额外的\两次。
回答by Rafi Kamal
You need to escape \character. So try
你需要转义\字符。所以试试
replaceAll("\\n", "\n");
回答by nhahtdh
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.
由于\n(或什至原始换行符 U+000A)在正则表达式中被解释为换行符,您需要\\n(转义\)指定斜杠\后跟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:
从编译器的角度来看,在 Java 字面量字符串中,需要转义\,所以我们再加一层转义:
String output = inputString.replaceAll("\\n", "\n");
// \n U+000A
回答by stan
replaceAllis using Regular Expressions, you can use replacewhich will also replace all '\n':
replaceAll正在使用正则表达式,您可以使用replace也将替换所有 '\n':
replace("\\n", "\n");

