Search code examples
compiler-errorscompilation

replaceAll method in java


I have a problem about using replaceAll method in my java app. I think there is a compile error, and the code is:

public static void main(String[] args) {
    String Str = " Welcome to Itpro.com please visit programming.itpro.com";
    System.out.println(Str.replaceAll(".com", ".net"));
}

and output is:

We.nete to Itpro.net please visit programming.itpro.net

welcome word has changed to we.nete and this is not correct.

When I change c letter in welcome word to capital C in str, everything is ok

I dont know what i do.


Solution

  • The first parameter passed to String#replaceAll() will be interpreted as a regular expression pattern. As the character . means any single letter, therefore .com will also match to Welcome. To get the behavior you want, you need to escape the dot with backslash:

    String str = "Welcome to Itpro.com please visit programming.itpro.com";
    System.out.println(str.replaceAll("\\.com", ".net"));