Search code examples
javastringreplaceall

string.replaceAll("\\n","") not working if string is taken as input from console and contains newline character


Case 1: Taking string input from scanner and replacing \n with -- (Not working)

Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
str = str.replaceAll("\n", "--");
System.out.println(str);

input: "UY9Q3HGjqYE1aHNIG+Rju2hS3WAAEFlakOSGZWffabFpWkeQ\nz4g6mfKoGVR2\nF1QkiHRMZfL4mCvChAuL7gCT3d3SrmxD6lBnOiWiFTPUz4Q=\n"

Case2: Same thing works if I directly assign string with same value as above.

String str = "UY9Q3HGjqYE1aHNIG+Rju2hS3WAAEFlakOSGZWffabFpWkeQ\nz4g6mfKoGVR2\nF1QkiHRMZfL4mCvChAuL7gCT3d3SrmxD6lBnOiWiFTPUz4Q=\n";
       
str = str.replaceAll("\n", "--");

PS: I have already tried using \n, line.separater


Solution

  •     String str = "Input\\nwith backslash and n";
        str = str.replaceAll("\\\\n", "--");
        System.out.println(str);
    

    Output:

    Input--with backslash and n

    We need to escape the backslash twice: To tell the regular expression that a literal backslash is intended we need to put two backslashes. And to tell the Java compiler that we intend literal backslashes in the string, each of those two needs to be entered as two backslashes. So we end up typing four of them.

    nextLine() reads one line, so the line cannot contain a newline character. So I have assumes that you were entering a backslash and an n as part of your input.

    Less confusing solution

    We don’t need to use any regular expression here, and doing that complicates the escaping business. So don’t.

        String str = "Input\\nwith backslash\\nand n\\n";
        str = str.replace("\\n", "--");
        System.out.println(str);
    

    Input--with backslash--and n--

    The replace method replaces all occurrences of the literal string given (in spite of not having All in the method name). So now we only need one escape, the one for the Java compiler.