Java用换行符替换所有
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4456707/
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 with newline symbol
提问by Kay
the newline symbol \n is causing me a bit of trouble when i try to detect and replace it: This works fine:
当我尝试检测和替换它时,换行符 \n 给我带来了一些麻烦:这很好用:
String x = "Bob was a bob \n";
String y = x.replaceAll("was", "bob");
System.out.println(y);
butt this code does not give the desired result
对接此代码没有给出所需的结果
String x = "Bob was a bob \n";
String y = x.replaceAll("\n", "bob");
System.out.println(y);
采纳答案by Dark Falcon
"Bob was a bob \\n"
becomes literally Bob was a bob \n
"Bob was a bob \\n"
变成字面意思 Bob was a bob \n
There is no newline to replace in the input string. Are you trying to replace a newline character or the escape sequence \\n
?
输入字符串中没有要替换的换行符。您是要替换换行符还是转义序列\\n
?
回答by Mat B.
Did you try this?:
你试过这个吗?:
x.replaceAll("\n", "bob");
You should escape the new line char before using it in replace function.
在替换函数中使用新行字符之前,您应该对其进行转义。
回答by JonMR
Your input string does not contain a new line. Instead it contains "\n". See the corrected input string below.
您的输入字符串不包含新行。相反,它包含“\n”。请参阅下面更正的输入字符串。
String x = "Bob was a bob \n";
String y = x.replaceAll("\n", "bob");
System.out.println(y);
回答by CoolBeans
This works as expected.
这按预期工作。
String str = "A B \n C";
String newStr = str.replaceAll("\n","Y");
System.out.println(newStr);
Prints:-
印刷:-
A B Y C
回答by Enrique
UPDATED:
更新:
I have modified it to work with multiple ocurrences of \n. Note that this may not be very efficient.
我已经修改它以处理多次出现的 \n。请注意,这可能不是很有效。
public static String replaceBob(String str,int index){
char arr[] = str.toCharArray();
for(int i=index; i<arr.length; i++){
if( arr[i]=='\' && i<arr.length && arr[i+1]=='n' ){
String temp = str.substring(0, i)+"bob";
String temp2 = str.substring(i+2,str.length());
str = temp + temp2;
str = replaceBob(str,i+2);
break;
}
}
return str;
}
I tried with this and it worked
我试过这个,它奏效了
String x = "Bob was a bob \n 123 \n aaa \n";
System.out.println("result:"+replaceBob(x, 0));
The first time you call the function use an index of 0.
第一次调用该函数时使用索引 0。
回答by Sam
String x = "Bob was a bob \n";
String y = x.replaceAll("was", "bob");
System.out.println(y);
one problem here: "\n" is not newline symbol. It should be:
这里有一个问题:“\n”不是换行符。它应该是:
String x = "Bob was a bob \n";// \n is newline symbol, on window newline is \r\n