I have a string with space and I want that space replace by "\_"
. For example here is my code 
String example = "Bill Gates";
example = example.replaceAll(" ","\\_");    
And the result of example is: "Bill_Gates" not "Bill\_Gates". When I try to do like this
String example = "Bill Gates";
example = example.replaceAll(" ","\\\\_");
The result of example is: "Bill\\_Gates" not "Bill\_Gates"
You need to use replaceAll(" ","\\\\_") instead of replaceAll(" ","\\_"). Because '\\' is a literal. It will be compiled as '\' single slash. When you pass this to replaceall method. It will take first slash as escaping character for "_". If you look inside replaceall method
    while (cursor < replacement.length()) {
        char nextChar = replacement.charAt(cursor);
        if (nextChar == '\\') {
            cursor++;
            if (cursor == replacement.length())
                throw new IllegalArgumentException(
                    "character to be escaped is missing");
            nextChar = replacement.charAt(cursor);
            result.append(nextChar);
            cursor++;
When it finds a single slash it will replace next character of that slash. So you have to input "\\\\_" to replace method. Then it will be processed as "\\_". Method will look first slash and replace second slash. Then it will replace underscore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With