Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a space exactly by "\_" in java String?

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"

like image 818
LeoPro Avatar asked Oct 27 '25 16:10

LeoPro


1 Answers

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.

like image 66
Buru Avatar answered Oct 30 '25 07:10

Buru