简体   繁体   中英

Why does the string ":n" considered same as ".n" by replaceAll() method in Java?

Why is :0 getting replaced when the statement is for .0 ?

I tried it with :x & .x and on my Intellij as well as on online gdb compiler, but this issue persists.

public class Main
{
    public static void main(String[] args) 
    {
        String s = "Hello:0, World:0.0, het:0";    
        System.out.println(s);

        s = s.replaceAll(".0,", ",");
        System.out.println(s);
    }
}

Output:

Hello:0, World:0.0, het:0
Hello, World:0, het:0

. means "any character", because replaceAll uses regular expressions .

Use replace instead, if you want to replace the literal string:

s = s.replace(".0,", ",");

Alternatively, you can escape the . , either by prefixing with \\ , or using the Pattern.quote method:

s = s.replaceAll("\\.0,", ",");
s = s.replaceAll(Pattern.quote(".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