简体   繁体   中英

Java replaceAll with newline symbol

the newline symbol \\n is causing me a bit of trouble 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);

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);

"Bob was a bob \\\\n" becomes literally 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 ?

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
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:

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

Did you try this?:

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

You should escape the new line char before using it in replace function.

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

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

UPDATED:

I have modified it to work with multiple ocurrences of \\n. Note that this may not be very efficient.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM