Java replaceAll with newline

the newline character \ n causes me a little problem when I try to detect and replace it: This works fine:

String x = "Bob was a bob \\n"; String y = x.replaceAll("was", "bob"); System.out.println(y); 

but 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); 
+4
source share
6 answers

"Bob was a bob \\n" literally becomes Bob was a bob \n

There is no new line in the input line. Are you trying to replace the newline character or the escape sequence \\n ?

+8
source

This works as expected.

 String str = "AB \n C"; String newStr = str.replaceAll("\\n","Y"); System.out.println(newStr); 

Print: -

 ABYC 
+3
source
 String x = "Bob was a bob \\n"; String y = x.replaceAll("was", "bob"); System.out.println(y); 

one problem: "\ n" is not a newline. It should be:

 String x = "Bob was a bob \n";// \n is newline symbol, on window newline is \r\n 
+1
source

Have you tried this ?:

 x.replaceAll("\\n", "bob"); 

Before using this function in a replacement function, you must exit the new char line.

0
source

Your input line does not contain a new line. Instead, it contains "\ n". See the corrected input line below.

 String x = "Bob was a bob \n"; String y = x.replaceAll("\n", "bob"); System.out.println(y); 
0
source

UPDATED:

I changed it to work with multiple appearances \ n. Please note that this may not be very effective.

 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 index 0.

-3
source

Source: https://habr.com/ru/post/1332292/


All Articles