Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The line

System.out.println("");

prints a single back-slash (). And

System.out.println("");

prints double back-slashes (\). Understood!

But why in the following code:

class ReplaceTest
{
    public static void main(String[] args)
    {
        String s = "hello.world";
        s = s.replaceAll("\.", "");
        System.out.println(s);
    }
}

is the output:

helloworld

instead of

hello\world

After all, the replaceAll() method is replacing a dot (\.) with (\\).

Can someone please explain this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
318 views
Welcome To Ask or Share your Answers For Others

1 Answer

When replacing characters using regular expressions, you're allowed to use backreferences, such as 1 to replace a using a grouping within the match.

This, however, means that the backslash is a special character, so if you actually want to use a backslash it needs to be escaped.

Which means it needs to actually be escaped twice when using it in a Java string. (First for the string parser, then for the regex parser.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...