Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading