Search code examples
javastringreplaceall

Why I am not able to replace "/abcd/" to "/xyz/" using string.replaceAll() method


I have a big string which has many url strings, I want to replace context of all urls. for example

https://host:port/sometext/abc

i want to replace /sometext/ with /newtext/ like this

mystring.replaceAll("/sometext/", "/newtext/");

I cant just search sometext and replace because sometext might have been used at many places.

But its not working even I tried replace method also but its also not working. Am I doing anything wrong?

Thanks in advance


Solution

  • In Java, String class is immutable. You can explore this at https://www.javatpoint.com/immutable-string. The answer for your question is the following code:

    String mystring = "https://host:port/sometext/abc";
    
    mystring = mystring.replaceAll("/sometext/", "/newtext/");
    
    System.out.println(mystring);